首页 > 解决方案 > 我正在尝试访问我制作的字典,以便该命令仅在字典中列出用户 ID 时运行

问题描述

我正在尝试访问我制作的字典,以便该命令仅在字典中列出用户 ID 时运行

到目前为止,这是我想出的,但它一直在失败:

import discord
client = discord.Client()

dict = {'rand ID 1':'rand ID 2', 'rand ID 3':'rand ID 4'} 

@client.event
async def on_message(message):
  if message.content.lower().startswith('.test'):
    if message.author.id == "dict":
      embed1 = discord.Embed(title='Hello World!')
      await message.channel.send(embed=embed1)

标签: discord.py

解决方案


您可能想使用 aset来存储 ID。

whitelisted_ids = {'rand ID 1', 'rand ID 2', 'rand ID 3', 'rand ID 4'}


此外,您可以使用谓词从命令本身中提取此行为。

whitelisted_ids = {'rand ID 1', 'rand ID 2', 'rand ID 3', 'rand ID 4'}
# Might be in capital if constant


class NotWithinWhitelist(commands.CheckFailure):
  pass


def is_within_whitelist():
  async def predicate(ctx):
    if ctx.author.id not in whitelisted_ids:
      raise NotWithinWhitelist("You are not whitelisted for that command")

    return True

  return commands.check(predicate)


@client.command()
@is_within_whitelist
async def test(ctx):
    test_embed = discord.Embed(title='Hello World!')
    await message.channel.send(embed=test_embed)


@test.error
async def test_error(ctx, error):
    if isinstance(error, commands.NotWithinWhitelist):
        await ctx.send(str(error))



推荐阅读