通过python向telegram bot发送mysql数据

dzhpxtsq  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(490)

我有一个问题,如何从mysql检索数据并通过python发布到telegrambot。mysql可以连接到python并在python终端上显示数据,但在电报中只显示行数。

  1. import time
  2. import random
  3. import datetime
  4. import telepot
  5. import MySQLdb
  6. from telepot.loop import MessageLoop
  7. db = MySQLdb.connect(host="127.0.0.1", # localhost
  8. user="cowrie", # username
  9. passwd="12345678", # password
  10. db="cowrie") # name of the data base
  11. cur = db.cursor()
  12. def handle(msg):
  13. chat_id = msg['chat']['id']
  14. command = msg['text']
  15. print 'Command received: %s' % command
  16. if command == '/about':
  17. bot.sendMessage(chat_id, 'Hi, I\'m netrapsystembot')
  18. elif command == '/random':
  19. bot.sendMessage(chat_id, random.randint(0,9))
  20. elif command == '/time':
  21. bot.sendMessage(chat_id, str(datetime.datetime.now()))
  22. elif command == '/sessions':
  23. bot.sendMessage(chat_id, cur.execute('SELECT ip FROM sessions'))
  24. for result in cur.fetchall():
  25. print result [0]
  26. bot = telepot.Bot('617662632:AAEGW74VAvZcjEpVCkiye8KLcv2xmSkt0L4')
  27. MessageLoop(bot, handle).run_as_thread()
  28. print 'Bot ready!'
  29. while 1:
  30. time.sleep(10)

python终端显示mysql的ip:

但电报只显示行数:

我要检索的数据是位于表会话中的ip地址。请帮忙。

2ekbmq32

2ekbmq321#

execute方法返回一个迭代器,而不是您要查找的结果。
请尝试以下操作:

  1. elif command == '/sessions':
  2. cur.execute('SELECT ip FROM sessions')
  3. for result in cur.fetchall():
  4. bot.sendMessage(chat_id, result [0])
ebdffaop

ebdffaop2#

非常感谢你的帮助。菲利普斯。。它可以工作,我可以从mysql检索数据。最后给出了ip地址的计算结果。
如果你能再帮我一次,如何让mysql数据库在数据插入数据库时自动(触发)将结果发送到电报。

相关问题