[Solved] NameError: name ‘command’ is not defined


It is hard to debug without more information, but I think the issue is the spacing of your function handle. You defined command inside of the function handle but are trying to access it without returning the variable handle or calling it until the end. This makes me believe that you have a spacing issue with your function entirely. Now your function handle will actually send a message after it is called, instead of just initializing two variables and not using them.

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)

However you are not passing a message into handle anywhere so the function will not execute in this current state.

0

solved NameError: name ‘command’ is not defined