当用户将代码发送到特定渠道或该机器人的DM's时,该机器人将如何向用户添加角色?
例如: 兑换xxx-xxxx-xxx 然后该机器人将为他提供角色客户
还可以多次使用同一代码进行保护吗?
答案 0 :(得分:0)
因此,我整理了一条命令,它将为您提供一个不错的起点。为了避免两次使用相同的代码,我将代码存储在一个文件中,一旦使用它,我将生成一个新的代码,然后重写该文件。这样,如果僵尸程序失去连接或断开连接,当前的有效代码不会丢失。
完整代码:
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发送命令的更多信息,此代码可在行会频道中工作。