0
votes

Is there any way how do that bot will add role to user when he sends code to a specific channel or to bot's DM'S?

For example: !redeem xxx-xxxx-xxx And then the bot will give him a role customer

Also is it possible to protect using the same code more than once?

1

1 Answers

0
votes

So I put together a command that will give you a decent starting point. As far as protecting against using the same code twice, I stored the code in a file and once it was used I generated a new one then overwrote the file. This way the current valid code is not lost if the bot loses connection or is disconnected.

Full code:

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'])

This code works in a guild channel, if you would like to read more about sending commands via DM this answer might help you.