【问题标题】:Is there a way for my discord bot to be used with one person at a time?有没有办法让我的不和谐机器人一次与一个人一起使用?
【发布时间】:2021-08-25 14:03:24
【问题描述】:

我正在用 python 制作一个猜谜游戏机器人,但多个人可以同时使用该机器人。我可以一次将其限制为一个可以使用该机器人的人吗?我希望得到一些相对容易理解的东西(如果可能的话)。

(我是 python 的初学者)

import keep_alive
import discord
import os
from discord.ext import commands
import random
import sys

client = commands.Bot(command_prefix=".")
number = random.randint(1, 100)

@client.event
async def on_ready():
    print("The bot is online")



@client.command()
async def numpuz(ctx):
  global steps
  await ctx.send("Type a starting number")
  steps = 0
  steps = 1
  global number
  print(number)
  global lives
  lives = 8
      
  @client.command()
  async def num(ctx, guessednumber):
    global steps
    global number
    global lives

        
    if int(guessednumber) > number: 
      if steps == 1:
        await ctx.send("Try again you were to high")
        lives = lives - 1
        if lives == 0:
          await ctx.send("YOU LOST")
          steps = 0
              
    elif int(guessednumber) < number:
      if steps == 1:
        await ctx.send("Try again you were to low")
        lives = lives - 1
        if lives == 0:
          await ctx.send("YOU LOST")
          steps = 0
            
    else:
      if steps == 1:
        await ctx.send("YOU WON")
        steps = 0
        number = random.randint(1, 100)
        await ctx.send("You had " +str(lives)+ " lives left")
        comm.reset_cooldown(ctx)
   

keep_alive.keep_alive()
client.run(os.getenv("token"))

【问题讨论】:

    标签: python discord bots


    【解决方案1】:

    在 Python 中,不建议像现在这样使用全局变量,这就是为什么每次都必须显式声明 global 的原因。更好的做法是为您的数字游戏创建一个类,然后将其导入,因为这样您就可以使用类属性而不是全局变量,而且它是更好的代码组织。

    不过,DiscordPy 还提供了另一种使用“全局”变量的方法,您可以详细阅读 here。基本上,你可以做

    bot = commands.Bot(command_prefix=".")
    bot.variable_name = 42
    
    @bot.command()
    async def foo(ctx):
       print(bot.variable_name)
    
    >> 42
    
    @bot.command()
    async def bar(ctx):
       bot.variable_name = "cheese"
       print(bot.variable_name)
    
    >> "cheese"
    

    至于对一个用户的限制,你可以做一些事情,比如跟踪用户的用户 ID 以启动 bot 命令,并且每当有人尝试使用 bot 命令时,检查他们是否具有相同的 ID:

    bot = commands.Bot(command_prefix=".")
    bot.allowed_id = "Not in use!"  
    
    @bot.command()
    async def numpuz(ctx):
       author = ctx.message.author
    
       if bot.allowed_id == "Not in use!":
          bot.allowed_id = author.id
    
       if bot.allowed_id != author.id:
          return   
    
       # The rest of your function here
    

    相同的 sn-p 将被添加到您的 num() 函数中。并且不要忘记将bot.allowed_id 设置回“未使用!”在某人完成命令后,例如输掉比赛。

    *Ps,Discord 客户端和机器人是分开的东西,所以你应该使用另一个变量名以避免混淆。像bot = commands.Bot(command_prefix=".") 这样的东西会更好。

    【讨论】:

    • 天哪,这正是我所需要的。非常感谢您的提示和帮助。 :)
    猜你喜欢
    • 2023-04-04
    • 2021-04-18
    • 2021-09-16
    • 1970-01-01
    • 2021-11-04
    • 2021-06-30
    • 2023-03-08
    • 2020-12-10
    • 2019-07-05
    相关资源
    最近更新 更多