0

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:

enter image description here

But telegram only shows number of row:

enter image description here

The data i want to retrieve is ip address that locate in table sessions. Please help.

1
  • Have you tried putting a breakpoint and debugging it ? Commented Jun 20, 2018 at 9:25

2 Answers 2

2

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])
Sign up to request clarification or add additional context in comments.

1 Comment

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? I am really glad if you can help.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.