如何使我的不一致机器人对正确答案做出回应?

时间:2020-01-02 21:35:25

标签: python discord.py

我正在编写一个机器人,该机器人在我的不和谐频道中询问琐事。我已经重写了几次,但是不能让它继续接受答案。 我可能想念一些可怕的东西。

我的代码:

# bot.py
import os
import json
import discord
from discord.ext import commands
import requests

token=('*removed*')
bot = commands.Bot(command_prefix ='??')
os.chdir(r'C:\Users\thund\OneDrive\Documenten\Python programmeren\Discord - bot')
correct_answer = ''

@bot.event
async def on_ready():
    print(f'{bot.user} has connected to Discord!')

@bot.event
async def on_member_join(member):

    with open('users.json', 'r') as f:
            users = json.load(f)
    await update_data(users, member)

    with open('users.json', 'w') as f:
            json.dump(users, f)

    await member.create_dm()
    await member.dm_channel.send(
        f'Hello {member.name}, You have joined a Discord server where the Mr. Questionnaire is active!\n')
    await member.dm_channel.send(
        f'By default you will get questions which you can answer by preceding your answer by ??')
    await member.dm_channel.send(
        f'There are different prices you can win, try answering some questions and find out!')

@bot.command()       
async def start(ctx):
    global correct_answer
    explanation = (
            'So you want to play a game? We will ask questions, the first one to answer wins one point\n'
            'I will keep firing questions, untill someone types ??stopplease'
            )
    await ctx.send(explanation)
    r = requests.get (url = 'https://opentdb.com/api.php?amount=1')
    data = r.json()
    category = data['results'][0]['category']
    difficulty = data['results'][0]['difficulty']
    question = data['results'][0]['question']
    answer = data['results'][0]['correct_answer']
    correct_answer = answer.replace(' ','_')
    await ctx.send('Category: %s\nDifficulty: %s\nQuestion: %s\n'
                    % (category, difficulty, question))

@bot.command()
async def correct(ctx):
    global correct_answer
    with open('users.json', 'r') as f:
        users = json.load(f)       
    await update_data(users, ctx.author)
    await add_experience(users, ctx.author, 10)
    await level_up(users, ctx.author, ctx.channel)
    with open('users.json', 'w') as f:
       json.dump(users, f)
    await ctx.send('{} has guessed correctly!'.format(ctx.author))
    bot.command('start')

async def update_data(users, user):
    if not user.id in users:
        users[user.id] = {}
        users[user.id]['experience'] = 0
        users[user.id]['level'] = 1

async def add_experience(users, user, exp):
    users[user.id]['experience'] += exp

async def level_up(users, user, channel):
    experience = users[user.id]['experience']
    lvl_start = users[user.id]['level']
    lvl_end = int(experience ** (1/4))

    if lvl_start < lvl_end:
        await ctx.send(channel, '{} has leveled up to level {}'.format(user.mention, lvl_end))
        users[user.id]['level'] = lvl_end

@bot.command(name='supersecret')
async def answer(ctx):
    global correct_answer
    await ctx.send('The Answer is: %s' % (correct_answer))

@bot.command(name='%s' % (correct_answer))
async def correct22(ctx):
        global correct_answer
        with open('users.json', 'r') as f:
            users = json.load(f)       
        await update_data(users, message.author)
        await add_experience(users, message.author, 10)
        await level_up(users, message.author, message.channel)
        with open('users.json', 'w') as f:
            json.dump(users, f)
        await ctx.send('{message.author} has guessed correctly!')

async def update_data(users, user):
    if not user.id in users:
        users[user.id] = {}
        users[user.id]['experience'] = 0
        users[user.id]['level'] = 1

async def add_experience(users, user, exp):
    users[user.id]['experience'] += exp

async def level_up(users, user, channel):
    experience = users[user.id]['experience']
    lvl_start = users[user.id]['level']
    lvl_end = int(experience ** (1/4))

    if lvl_start < lvl_end:
        await bot.send_message(channel, '{} has leveled up to level {}'.format(user.mention, lvl_end))
        users[user.id]['level'] = lvl_end

@bot.command(name='stopplease', help='Stop it right now!')
async def stop_quiz(ctx):
    await ctx.send('Thank you for playing our game!\n'
                   'If you like it, please consider a donation and/or using it on all the servers you know!')

@bot.event
async def on_error(event, *args, **kwargs):
    with open('err.log', 'a') as f:
        if event == 'on_message':
            f.write(f'Unhandled message: {args[0]}\n')
        elif event == 'command':
            f.write(f'Unhandled command: {args[0]}\n')
        else:
            raise
bot.run(token)

我尝试添加一些命令,希望可以在上面执行这些命令,但是我完全错过了一些东西。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您的问题是对装饰工的误解。它们是一个非常复杂的主题,因此这里是basic resource。对您来说,最重要的是以下内容:装饰器仅运行一次一次,这意味着只要您运行文件,装饰器中的内容便是它唯一会听的东西。 现在,您要在代码中尝试做的事情

@bot.command(name='%s' % (correct_answer))

在装饰器中具有动态值,因此漫游器会响应正确的答案。这行不通!装饰器只能运行一次。

那我们该如何解决呢? 我们需要重新编写您的正确的22函数。您的机器人可以通过参数处理动态输入。幸运的是,在bot扩展中,这些操作非常容易。 为了甚至有参数,我们仍然需要一个命令名,因此让我们选择“答案”。因此,在尝试用??2005回答之前,现在用??answer 2005回答。您可以尝试按照最初的意图进行操作,但是在我看来,这会使您的代码过于复杂,因为您必须处理消息处理程序。

可能的解决方案:

@bot.command(name='answer')
async def correct22(ctx, answer):
        global correct_answer
        if correct_answer != answer:
            return
        with open('users.json', 'r') as f:
            users = json.load(f)       
        await update_data(users, message.author)
        await add_experience(users, message.author, 10)
        await level_up(users, message.author, message.channel)
        with open('users.json', 'w') as f:
            json.dump(users, f)
        await ctx.send('{message.author} has guessed correctly!')

我还没有测试过用户功能(例如体验),但是消息应答至少应该像这样工作。