我想通过python将MSSQL数据发送到电报bot。这是我到目前为止所写的:
import time
import random
import datetime
import telepot
from telepot.loop import MessageLoop
import pyodbc
conn = pyodbc.connect('Driver={SQL Server};'
'Server=DESKTOP-OM8N0ER\SQLEXPRESS01;'
'Database=SmartHome;'
'Trusted_Connection=yes;')
cursor = conn.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':
cursor.execute('SELECT * FROM SmartHome.dbo.SensorData')
for result in cursor.fetchall():
bot.sendMessage(chat_id, result [0])
bot = telepot.Bot('803777982:AAEmtO98wjYcqoFqWXOSuYTeg6HFG6xUnwk')
MessageLoop(bot,handle).run_as_thread()
print ('Bot ready!')
while 1:
time.sleep(10)
但是我目前在此行收到此错误消息:
print ('Command received: %s') % command
NameError:名称“ command”未定义
答案 0 :(得分:0)
没有更多信息很难调试,但是我认为问题在于函数句柄的间距。您在函数句柄内部定义了命令,但尝试访问它而不返回变量句柄或一直调用到最后。这使我相信您的功能完全存在间距问题。现在,您的函数句柄实际上将在调用后发送一条消息,而不是仅初始化两个变量而不使用它们。
import time
import random
import datetime
import telepot
from telepot.loop import MessageLoop
import pyodbc
conn = pyodbc.connect('Driver={SQL Server};'
'Server=DESKTOP-OM8N0ER\SQLEXPRESS01;'
'Database=SmartHome;'
'Trusted_Connection=yes;')
cursor = conn.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':
cursor.execute('SELECT * FROM SmartHome.dbo.SensorData')
for result in cursor.fetchall():
bot.sendMessage(chat_id, result [0])
bot = telepot.Bot('803777982:AAEmtO98wjYcqoFqWXOSuYTeg6HFG6xUnwk')
MessageLoop(bot,handle).run_as_thread()
print ('Bot ready!')
while 1:
time.sleep(10)
但是,您没有将消息传递到任何地方的句柄中,因此该功能不会在当前状态下执行。