【发布时间】:2020-02-26 23:06:00
【问题描述】:
当该机器人将代码发送到特定频道或机器人的 DM'S 时,该机器人如何为用户添加角色?
例如: !redeem xxx-xxxx-xxx 然后机器人会给他一个角色客户
还可以多次使用相同的代码进行保护吗?
【问题讨论】:
标签: bots discord discord.py
当该机器人将代码发送到特定频道或机器人的 DM'S 时,该机器人如何为用户添加角色?
例如: !redeem xxx-xxxx-xxx 然后机器人会给他一个角色客户
还可以多次使用相同的代码进行保护吗?
【问题讨论】:
标签: bots discord discord.py
所以我整理了一个命令,可以为您提供一个不错的起点。至于防止两次使用相同的代码,我将代码存储在一个文件中,一旦使用它,我生成一个新的然后覆盖文件。这样,如果机器人失去连接或断开连接,当前的有效代码不会丢失。
完整代码:
import discord
from discord.ext import commands
import string
import random
client = commands.Bot(command_prefix='!')
@client.command(pass_context=True)
async def redeem(ctx, code='xxx-xxxx-xxx'):
# opens the file that holds the key
with open('key_codes', 'r') as key_codes:
# the first line in the file holds the key and only the key
key = key_codes.readline()
# if the code given and the actual key are equal then give the user the customer role and generate a new key
if code == key:
await ctx.author.add_roles(discord.utils.get(ctx.guild.roles, name='Customer'))
# all letters (upper and lower) and digits to build the new code from
chars = string.ascii_letters + string.digits
# creates the key string
key = (''.join(random.choice(chars) for i in range(3)) + '-' + ''.join(random.choice(chars) for i in range(4)) + '-' + ''.join(random.choice(chars) for i in range(3)))
# opens the file and writes the new code to it, opening a file in mode 'w' overrites the file rather than appending (old key is lost)
with open('key_codes', 'w') as key_codes:
key_codes.write(key)
# if the code given does not match the key we send the channel a message
else:
await ctx.channel.send("This code is not valid!")
client.run(os.environ['DISCORD_TOKEN'])
此代码适用于公会频道,如果您想了解更多关于通过 DM 发送命令的信息this answer 可能会对您有所帮助。
【讨论】: