【问题标题】:Discord bot - giving roles after gets secret codeDiscord bot - 在获得密码后赋予角色
【发布时间】:2020-02-26 23:06:00
【问题描述】:

当该机器人将代码发送到特定频道或机器人的 DM'S 时,该机器人如何为用户添加角色?

例如: !redeem xxx-xxxx-xxx 然后机器人会给他一个角色客户

还可以多次使用相同的代码进行保护吗?

【问题讨论】:

    标签: bots discord discord.py


    【解决方案1】:

    所以我整理了一个命令,可以为您提供一个不错的起点。至于防止两次使用相同的代码,我将代码存储在一个文件中,一旦使用它,我生成一个新的然后覆盖文件。这样,如果机器人失去连接或断开连接,当前的有效代码不会丢失。

    完整代码:

    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 可能会对您有所帮助。

    【讨论】:

    • 谢谢哥们,但是有可能让它从网络托管的文件中挑选代码吗?例如在 www.name.com/codes/codes.txt
    • 您可以使用漂亮的汤来解析网页中的特定元素。您实际上会将漂亮的汤传递给您想要查看的网页,然后指定要在页面上查找的元素。 Pypi pageDocumentation
    猜你喜欢
    • 2021-10-11
    • 2021-08-09
    • 1970-01-01
    • 2022-01-09
    • 2018-07-24
    • 2021-04-15
    • 2021-06-14
    • 2020-07-31
    • 2020-06-29
    相关资源
    最近更新 更多