I’m building a Discord chat bot using Tkinter for the interface. I want to create a button that, when pressed, sends a message to the linked server. The button appears fine, but I encounter an error upon clicking it.
The error message I receive is:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python39\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "C:\Users\Developer\Desktop\chatbot.py", line 95, in buttonClick
send_chat_message(SERVER_CHANNEL, "Button pressed!")
File "C:\Users\Developer\Desktop\chatbot.py", line 25, in send_chat_message
connection.send(bytes('PRIVMSG %s :%s\r\n' % (channel, text), 'UTF-8'))
NameError: name 'connection' is not defined
Interestingly, all my other bot commands work perfectly. Here are the message-sending functions I have defined:
def send_ping_response(message):
connection.send(bytes('PONG %s\r\n' % message, 'UTF-8'))
def send_chat_message(channel, text):
connection.send(bytes('PRIVMSG %s :%s\r\n' % (channel, text), 'UTF-8'))
def set_nickname(name):
connection.send(bytes('NICK %s\r\n' % name, 'UTF-8'))
def authenticate(token):
connection.send(bytes('PASS %s\r\n' % token, 'UTF-8'))
def connect_to_channel(channel):
connection.send(bytes('JOIN %s\r\n' % channel, 'UTF-8'))
def leave_channel(channel):
connection.send(bytes('PART %s\r\n' % channel, 'UTF-8'))
And here’s how I set up my button:
root = Tk()
def buttonClick():
send_chat_message(SERVER_CHANNEL, "Button pressed!")
testButton = Button(root, text="Send Message", command=buttonClick)
testButton.pack()
root.mainloop()
Could someone help clarify why this scope problem occurs with the button in the GUI but not in other sections of my code?