我有问题,如何从Mysql检索数据,并通过Python发布到Telegram机器人。Mysql可以连接到Python,并在Python终端显示数据,但在电报中,它只显示行数。
import time
import random
import datetime
import telepot
import MySQLdb
from telepot.loop import MessageLoop
db = MySQLdb.connect(host="127.0.0.1", # localhost
user="cowrie", # username
passwd="12345678", # password
db="cowrie") # name of the data base
cur = db.cursor()
def handle(msg):
chat_id = msg['chat']['id']
command = msg['text']
print 'Command received: %s' % command
if command == '/about':
bot.sendMessage(chat_id, 'Hi, I\'m netrapsystembot')
elif command == '/random':
bot.sendMessage(chat_id, random.randint(0,9))
elif command == '/time':
bot.sendMessage(chat_id, str(datetime.datetime.now()))
elif command == '/sessions':
bot.sendMessage(chat_id, cur.execute('SELECT ip FROM sessions'))
for result in cur.fetchall():
print result [0]
bot = telepot.Bot('617662632:AAEGW74VAvZcjEpVCkiye8KLcv2xmSkt0L4')
MessageLoop(bot, handle).run_as_thread()
print 'Bot ready!'
while 1:
time.sleep(10)
Python终端显示来自mysql的ip:
但电报只显示行数:
我要检索的数据是位于表会话中的ip地址。请帮帮忙。
发布于 2018-06-20 17:39:42
execute方法返回迭代器,而不是您要查找的结果。
尝试以下操作:
elif command == '/sessions':
cur.execute('SELECT ip FROM sessions')
for result in cur.fetchall():
bot.sendMessage(chat_id, result [0])
发布于 2018-06-21 16:01:11
非常感谢你的帮助S. Phillips..它可以工作,我可以从mysql中检索数据。最后显示了IP地址的计算结果。
如果你能再帮我一次,如何使MySQL数据库在数据插入到数据库时自动(触发)将结果发送到电报。
https://stackoverflow.com/questions/50944601
复制相似问题