Discord Python Bot With Different Source Files

2.4k Views Asked by At

So I'm having trouble with my Discord Bot in Python.

The code for it became just too much for having a good overview, so I wanted to split it up into different source-files.

(Main-File)

...        
import second_file
if message.content.lower().startswith("!Hi"):
    second_file.hello()

(Second-File)

...
from __main__ import client
def hello():
    await client.send_message(message.channel, "Hiii <3!")

The error I am getting is name "client" is not defined.

What should I do? Thanks :)

2

There are 2 best solutions below

16
James On BEST ANSWER

Try replacing from __main__ import client with from main import client assuming your main python file is called main.py.

You need to do this because python wants just the file name when importing another script. I would also recommend changing your main file name to something else as __main__ in python is reserved for other things.

0
QHpix On

I had the same problem. The problem is that you are using await outside of an async function. I don't know the real reason why that throws the error though. You also don't necessarily need to import client from __main__. You can use

await __main__.client.send_message(__main__.message.channel, 'Hello')` 

just fine. But try this code:

(Main-file)
import second_file
if message.content.lower().startswith('!hi'):
    second_file.hello()

(Second-file)

async def hello():
    await __main__.client.send_message(__main__.message.channel, 'Hello!')

Sorry if i have any grammatical, or spelling mistakes. English isn't my native language (unfortunataly D: ) Hope this helps you as well