How to use commands only when a current command is triggered?

六眼飞鱼酱① 提交于 2019-12-11 05:59:31

问题


This question might be complicated and my brain can't really explain it well so please bare with this crappy explanation, My question, When you trigger a command for example .start it will start let's say a text based game, of course you would have the commands to be able to actually play the game however my concern is people can still trigger the ingame commands without needing to start the game for example .

     if message.content.startswith("/play"):       #Here is the play command where you execute the game to start
         await client.send_message(message.channel, "Welcome to the game!")
     if message.content.startswith("/examine):
         await client.send_message(message.channel, "You examined the rock and well, got a rock!") #In-Game commands/movements

What i'm saying is, is there a way of only being able to use the in-game commands only when the game itself is activated? Additional Question: How would you store a user's information like basically saving the game (You don't really need to answer this as i would like to learn this myself but any tips would be great!)


回答1:


First, we want some object that stores the state of a particular session. We can just call this object Game. We'll maintain a mapping of discord.Users to Games. A User existing in this mapping means that they are playing the game. Some basics would look something like:

from discord.ext import commands

class Game:
    def __init__(self):
        self.points = 0
        self.inventory = []

bot = commands.Bot('/')

sessions = {}

@bot.command(pass_context=True)
async def play(ctx):
    if ctx.message.author.id in sessions:
        await bot.say("You're already playing")
        return
    sessions[ctx.message.author.id] = Game()
    await bot.say("Welcome to the game!")

@bot.command(pass_context=True)
async def quit(ctx):
    if ctx.message.author.id not in sessions:
        await bot.say("You're not playing the game")
        return
    del sessions[ctx.message.author.id]
    await bot.say("Game Over")

@bot.command(pass_context=True)
async def examine(ctx):
    session = sessions.get(ctx.message.author.id, None)
    if session is None:
        await bot.say("You're not playing the game")
        return
    session.inventory.append("A rock")
    await bot.say("You examined the rock and well, got a rock!")

bot.run("TOKEN")

Some things you could do to extend this: make use of checks and CommandErrors to avoid having to repeat the code for checking sessions; make sure that Games are pickleable, and write code for saving games using pickle; write a game that's more fun than collecting rocks.



来源:https://stackoverflow.com/questions/51112373/how-to-use-commands-only-when-a-current-command-is-triggered

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!