Python - 显示消息是输入了错误的命令 (Discord.py)
Python - Displaying message is wrong command entered (Discord.py)
我目前运行下面的代码在字典中查找项目(通道名称、命令和包含要输出的数据的文本文件路径)。
下面是我之前使用的代码,它工作正常,但是当输入字典中不存在的命令时,Discord 中没有显示消息。
for id, info in dict.items():
if str(message.channel) == info["channel"]:
print(info["channel"])
if message.content.find (info["command"]) != -1:
print(info["command"])
print(info["textfile"])
with open(info["textfile"], 'r') as file:
msg = file.read().strip().split ("--------------------")
await message.channel.send("Info sent in DM")
for item in msg:
print (item)
await message.author.send(item)
此代码工作正常,但我希望在用户输入不在其中一个字典条目中的命令时以不和谐的方式向用户显示一条消息。我尝试添加 if elif 语句,如下面的代码所示,但我收到的输出是输出“不正确的命令”的无限循环。即使命令是字典中的值,也似乎使用下面的代码输出“不正确的命令”。
dict = {"boxingchannel" : {"channel": "boxingmma", "command": "!boxing", "textfile":"/var/output/boxingtest.txt" },
"footballchannel" : {"channel": "football", "command": "!english", "textfile":"/var/output/englandtest.txt" },
"helpchannel" : {"channel": "general", "command": "!buffer", "textfile":"/home/brendan/Desktop/Python/tryfirst.txt"}
}
for id, info in dict.items():
if str(message.channel) == info["channel"]:
print(info["channel"])
if str(message.content.find) == (info["command"]):
print(info["command"])
print(info["textfile"])
with open(info["textfile"], 'r') as file:
msg = file.read().strip().split ("--------------------")
await message.channel.send("Info sent in DM")
for item in msg:
print (item)
await message.author.send(item)
elif str(message.content.find) != (info["command"]):
await message.channel.send("Incorrect command")
感谢任何可以为此问题提供帮助或解决方案的人。
更新:
我能够使用 Mr_Spaar 友情提供的第一部分代码。这在不和谐中按预期输出,但是当我检查终端时出现以下错误:
File "discordbot4.py", line 72, in on_message
await message.author.send("Wrong command")
AttributeError: 'ClientUser' object has no attribute 'send'
我查看了这个错误,看到有一个讨论指出客户端没有 class 发送,但我不确定我需要做什么或调查什么来防止这个错误被显示。
感谢任何可以提供帮助解决问题的人。
完整代码:
import discord
import os
from dotenv import load_dotenv
client = discord.Client()
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')
client = discord.Client()
@client.event
async def on_ready():
for guild in client.guilds:
if guild.name == GUILD:
break
print(
f'{client.user} is connected to the following guild:\n'
f'{guild.name}(id: {guild.id})'
)
@client.event
async def on_member_join(member):
await member.send("```Welcome to Sports Schedule server. \n This is a bot only server which you can send messages and automatically receive a response. \nCommands accepted by bot can be found by sending message !help in any of the channels. \n Enjoy your stay.```")
@client.event
async def on_message(message):
id = client.get_guild(731946041****229982)
online = 0
idle = 0
offline = 0
if message.content == "!users":
for m in id.members:
if str(m.status) == "online":
online += 1
if str(m.status) == "offline":
offline += 1
else:
idle += 1
await message.channel.send(f"```Online: {online}.\nIdle/busy/dnd: {idle}.\nOffline: {offline} .\nTotal Members: {id.member_count}```")
dict = {"boxingchannel" : {"channel": "boxingmma", "command": "!boxing", "textfile":"/var/output/boxingtest.txt" },
"footballchannel" : {"channel": "football", "command": "!english", "textfile":"/var/output/englandtest.txt" },
"helpchannel" : {"channel": "general", "command": "!buffer", "textfile":"/home/brendan/Desktop/Python/tryfirst.txt"}
}
for id, info in dict.items():
if str(message.channel) == info["channel"]:
print(info["channel"])
if message.content.find (info["command"]) != -1:
print(info["command"])
print(info["textfile"])
with open(info["textfile"], 'r') as file:
msg = file.read().strip().split ("--------------------")
await message.channel.send("Info sent in DM")
for item in msg:
print (item)
await message.author.send(item)
return
await message.author.send("Wrong command")
client.run("NzMxOTQ4Mzk5N*****jY3NDg2.XwuPsw.iNu1Ju-e2yDnRS_uWqff43Thvqw")
你可以这样做,如果找到命令则使用return
:
for id, info in dict.items():
if str(message.channel) == info["channel"]:
print(info["channel"])
if message.content.find (info["command"]) != -1:
print(info["command"])
print(info["textfile"])
with open(info["textfile"], 'r') as file:
msg = file.read().strip().split ("--------------------")
await message.channel.send("Info sent in DM")
for item in msg:
print (item)
await message.author.send(item)
return
await message.author.send("Wrong command entered")
但是,使用 on_message
事件创建命令并不是最佳选择,您可以使用 commands
框架:
from discord.ext import commands
@commands.command(aliases=["english", "football"])
async def buffer(ctx):
command_list = {
"boxing" : {"channel": "boxingmma", "textfile":"/var/output/boxingtest.txt" },
"english" : {"channel": "football", "textfile":"/var/output/englandtest.txt" },
"buffer" : {"channel": "general", "textfile":"/home/brendan/Desktop/Python/tryfirst.txt"},
}
try:
command = command_list[ctx.invoked_with]
if ctx.channel.name == command['channel']:
with open(command["textfile"], 'r') as file:
msg = file.read().strip().split("--------------------")
await ctx.send("Info sent in DM")
await message.author.send('\n'.join(msg))
return
await ctx.send("Wrong channel!")
except:
await ctx.send("Wrong command!")
我目前运行下面的代码在字典中查找项目(通道名称、命令和包含要输出的数据的文本文件路径)。
下面是我之前使用的代码,它工作正常,但是当输入字典中不存在的命令时,Discord 中没有显示消息。
for id, info in dict.items():
if str(message.channel) == info["channel"]:
print(info["channel"])
if message.content.find (info["command"]) != -1:
print(info["command"])
print(info["textfile"])
with open(info["textfile"], 'r') as file:
msg = file.read().strip().split ("--------------------")
await message.channel.send("Info sent in DM")
for item in msg:
print (item)
await message.author.send(item)
此代码工作正常,但我希望在用户输入不在其中一个字典条目中的命令时以不和谐的方式向用户显示一条消息。我尝试添加 if elif 语句,如下面的代码所示,但我收到的输出是输出“不正确的命令”的无限循环。即使命令是字典中的值,也似乎使用下面的代码输出“不正确的命令”。
dict = {"boxingchannel" : {"channel": "boxingmma", "command": "!boxing", "textfile":"/var/output/boxingtest.txt" },
"footballchannel" : {"channel": "football", "command": "!english", "textfile":"/var/output/englandtest.txt" },
"helpchannel" : {"channel": "general", "command": "!buffer", "textfile":"/home/brendan/Desktop/Python/tryfirst.txt"}
}
for id, info in dict.items():
if str(message.channel) == info["channel"]:
print(info["channel"])
if str(message.content.find) == (info["command"]):
print(info["command"])
print(info["textfile"])
with open(info["textfile"], 'r') as file:
msg = file.read().strip().split ("--------------------")
await message.channel.send("Info sent in DM")
for item in msg:
print (item)
await message.author.send(item)
elif str(message.content.find) != (info["command"]):
await message.channel.send("Incorrect command")
感谢任何可以为此问题提供帮助或解决方案的人。
更新:
我能够使用 Mr_Spaar 友情提供的第一部分代码。这在不和谐中按预期输出,但是当我检查终端时出现以下错误:
File "discordbot4.py", line 72, in on_message
await message.author.send("Wrong command")
AttributeError: 'ClientUser' object has no attribute 'send'
我查看了这个错误,看到有一个讨论指出客户端没有 class 发送,但我不确定我需要做什么或调查什么来防止这个错误被显示。
感谢任何可以提供帮助解决问题的人。
完整代码:
import discord
import os
from dotenv import load_dotenv
client = discord.Client()
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')
client = discord.Client()
@client.event
async def on_ready():
for guild in client.guilds:
if guild.name == GUILD:
break
print(
f'{client.user} is connected to the following guild:\n'
f'{guild.name}(id: {guild.id})'
)
@client.event
async def on_member_join(member):
await member.send("```Welcome to Sports Schedule server. \n This is a bot only server which you can send messages and automatically receive a response. \nCommands accepted by bot can be found by sending message !help in any of the channels. \n Enjoy your stay.```")
@client.event
async def on_message(message):
id = client.get_guild(731946041****229982)
online = 0
idle = 0
offline = 0
if message.content == "!users":
for m in id.members:
if str(m.status) == "online":
online += 1
if str(m.status) == "offline":
offline += 1
else:
idle += 1
await message.channel.send(f"```Online: {online}.\nIdle/busy/dnd: {idle}.\nOffline: {offline} .\nTotal Members: {id.member_count}```")
dict = {"boxingchannel" : {"channel": "boxingmma", "command": "!boxing", "textfile":"/var/output/boxingtest.txt" },
"footballchannel" : {"channel": "football", "command": "!english", "textfile":"/var/output/englandtest.txt" },
"helpchannel" : {"channel": "general", "command": "!buffer", "textfile":"/home/brendan/Desktop/Python/tryfirst.txt"}
}
for id, info in dict.items():
if str(message.channel) == info["channel"]:
print(info["channel"])
if message.content.find (info["command"]) != -1:
print(info["command"])
print(info["textfile"])
with open(info["textfile"], 'r') as file:
msg = file.read().strip().split ("--------------------")
await message.channel.send("Info sent in DM")
for item in msg:
print (item)
await message.author.send(item)
return
await message.author.send("Wrong command")
client.run("NzMxOTQ4Mzk5N*****jY3NDg2.XwuPsw.iNu1Ju-e2yDnRS_uWqff43Thvqw")
你可以这样做,如果找到命令则使用return
:
for id, info in dict.items():
if str(message.channel) == info["channel"]:
print(info["channel"])
if message.content.find (info["command"]) != -1:
print(info["command"])
print(info["textfile"])
with open(info["textfile"], 'r') as file:
msg = file.read().strip().split ("--------------------")
await message.channel.send("Info sent in DM")
for item in msg:
print (item)
await message.author.send(item)
return
await message.author.send("Wrong command entered")
但是,使用 on_message
事件创建命令并不是最佳选择,您可以使用 commands
框架:
from discord.ext import commands
@commands.command(aliases=["english", "football"])
async def buffer(ctx):
command_list = {
"boxing" : {"channel": "boxingmma", "textfile":"/var/output/boxingtest.txt" },
"english" : {"channel": "football", "textfile":"/var/output/englandtest.txt" },
"buffer" : {"channel": "general", "textfile":"/home/brendan/Desktop/Python/tryfirst.txt"},
}
try:
command = command_list[ctx.invoked_with]
if ctx.channel.name == command['channel']:
with open(command["textfile"], 'r') as file:
msg = file.read().strip().split("--------------------")
await ctx.send("Info sent in DM")
await message.author.send('\n'.join(msg))
return
await ctx.send("Wrong channel!")
except:
await ctx.send("Wrong command!")