Reputation: 25
I made my Discord bot read text messages and respond to certain words, either with text or pictures. Since I'll probably make it react to a lot of words I wondered if there is a better way to implement multiple if statements like this:
@client.event
async def on_message(message):
print(message.author.id, message.author)
if client.user.id != message.author.id:
if 'foo' in message.content:
await message.channel.send('bar')
if 'hello' in message.content:
await message.channel.send('hey')
if 'cat' in message.content:
await message.channel.send(file=discord.File('cat.png'))
await client.process_commands(message)
Any suggestions?
Upvotes: 0
Views: 84
Reputation: 77
You can use lists like this
@client.event
async def on_message(message):
print(message.author.id, message.author)
if client.user.id != message.author.id:
msg = ['foo', 'hello', 'cat']
res = ['bar', 'hey', discord.File('cat.png')]
if message.content in msg:
a = msg.index(message.content)
await message.channel.send(res[a])
await client.process_commands(message)
Upvotes: 1
Reputation: 690
For my opinion, it is ok.
You can also use a dictionary for such things. Something like this:
reactions_dict={'foo': 'bar',
'hello': 'hey',
'cat': discord.File('cat.png')}
for k,v in reactions_dict.items():
if k in message.content:
message.channel.send(v)
But I'm not here to say that this is the best choice in any situation. It's depends on the logic and complexity of the conditions.
PS: In addition, in python 3.10, there will be a "case" and "match" syntax" https://www.python.org/dev/peps/pep-0634/
Upvotes: 1