我目前正在研究Discord机器人。我希望机器人记录它在特定频道上发送的所有消息。如果发送了特定的文本命令,我希望机器人删除所有消息,然后删除文本命令所针对的消息,然后再次发送消息。
当前代码:
import discord
current_queue = "current-queue"
current_queue_id = "454938696064696322"
join_channel = "join-queue"
queue_msgs = []
currently_queued_name = []
currently_queued_disc = []
client = discord.Client()
@client.event
async def on_message(message):
if message.author == client.user:
if str(message.channel) == current_queue:
queue_msgs.append(message)
if message.author != client.user:
await printer(message)
if str(message.channel) == join_channel:
if message.content.startswith("!join"):
await join(message)
elif message.content.startswith("!leave"):
await leave(message, queue_msgs)
else:
await client.delete_message(message)
async def join(message):
await client.delete_message(message)
currently_queued_name.append(message.author.name)
currently_queued_disc.append(message.author.discriminator)
await client.send_message(discord.Object(id=current_queue_id), message.author.mention)
print("Manager has assigned {} to the queue.".format(message.author))
async def leave(message, queue_msgs):
await client.delete_message(message)
if message.author.name in currently_queued_name:
for i in range(len(queue_msgs)):
print(str(queue_msgs[i]))
await client.delete_message(queue_msgs[i])
queue_msgs = []
print("Manager has deleted queue.")
pos = currently_queued_name.index(message.author.name)
del currently_queued_name[pos]
del currently_queued_disc[pos]
for i in range(len(currently_queued_name)):
user = discord.utils.get(message.server.member, name="{}".format(currently_queued_name[i]), discriminator="{}".format(currently_queued_disc[i]))
await client.send_message(discord.Object(id=current_queue_id), user.mention)
print("Manager has updated queue.")
这是我第一次尝试!join
后跟!leave
。但是,如果要再次执行此操作!join
,那么!leave
上会失败:
NOT FOUND (status code: 404): Unknown Message
答案 0 :(得分:0)
在z-index
中,您有以下几行:
<a>
实际上,async def leave(...)
尚未删除,因为您只是在本地范围内重新定义queue_msgs = []
print("Manager has deleted queue.")
变量。因此,第二次运行该函数时,它会尝试删除已删除的消息。如果您想通过引用清除queue_msgs
,请将其更改为以下内容:
queue_msgs
以这种方式执行此操作时,您甚至不需要将queue_msgs
传递给函数,因为它已经在全局范围内。 queue_msgs.clear()
print("Manager has deleted queue.")
应该足够了。
附注:您应该查看queue_msgs
扩展程序,这有助于您处理async def leave(message):
和discord.ext.commands
等命令。