Reputation: 3
I have problem, how to retrieve data from Mysql and post to Telegram Bot via Python. Mysql can connect to the Python and show the data in Python terminal but in telegram, it only shows number of rows only.
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 terminal show the ip from mysql:
But telegram only shows number of row:
The data i want to retrieve is ip address that locate in table sessions. Please help.
Upvotes: 0
Views: 7208
Reputation: 3
Thanks a lot for your help S. Phillips.. it works and i can retrieve the data from mysql. It finally shows the result of IP address.
And if you can help me one more time, how to make the MySQL database send the result automatically(trigger) to the telegram when data INSERT into database.
Upvotes: 0
Reputation: 58
The execute method returns an iterator rather than the result you are looking for.
Try the following:
elif command == '/sessions':
cur.execute('SELECT ip FROM sessions')
for result in cur.fetchall():
bot.sendMessage(chat_id, result [0])
Upvotes: 2