[英]I am currently learning to make a discord bot. I want to create a switch statement
import os
import discord
client = discord.Client()
@client.event
async def on_ready():
print('we have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$Hello'):
await message.channel.send('Hello! write "$Help" to find more about the Noriku bot ')
if message.content.startswith('$Help'):
await message.channel.send('Hi again! The noriku bot is still in beta stages...the only 2 commands are $Hello and $Help')
client.run(os.getenv('token'))
我想做的是做 switch 語句,因為許多專業人士說這比做 if 語句更好
Python 沒有 switch-case 語句。 無論如何,在您的情況下沒有必要,因為您的代碼已經可讀,並且 switch-case 將不適用,因為您使用的是 function ( .startswith()
)。 Switch-case 語句僅在特定情況下“更好”。 鑒於您只檢查 2 個條件,這種方法已經是最好的了。
但是,如果您要增加條件的數量,則應該通過將字符串放入字典等數據結構中來重構它,這樣您就不會一直重復您的代碼。
commands = {
'$Hello' : 'Hello! write "$Help" to find more about the Noriku bot ',
'$Help' : 'Hi again! The noriku bot is still in beta stages...the only 5 commands are $Hello, $Help, $Test1, $Test2, and $Test3',
'$Test1' : 'This is Test1',
'$Test2' : 'This is Test2',
'$Test3' : 'This is Test3'
}
...
@client.event
async def on_message(message):
if message.author == client.user:
return
for key, value in commands.items():
if message.content.startswith(key):
await message.channel.send(value)
這樣,您就不必為您所做的每個命令都添加額外的 if 語句。
一旦您對這些感到滿意,您可能需要查看Commands 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.