代码之家  ›  专栏  ›  技术社区  ›  tristan360

如何让python存储多人的数据?[已关闭]

  •  -1
  • tristan360  · 技术社区  · 6 年前

    我想挑起争端。py async机器人,当有人要求时,它会给人以布朗尼点数(嘿嘿)。它应该是我和我的朋友的本地机器人,但我不想每次重新启动它时都将每个人的每个布朗尼点都更新到代码中。我的代码在这里:

    导入命令

    import discord
    from discord.ext.commands import Bot
    from discord.ext import commands
    import asyncio
    import time
    import random
    
    #Here is the basic command:
    #await client.send_message(message.channel, messsage)
    
    #global hub
    me = 0
    discordname = "PRIVATE"
    
    Client = discord.Client()
    client = commands.Bot(command_prefix = "")
    
    @client.event
    async def on_ready():
        print ("the brownies are loaded and ready to go!")
    
    @client.event
    async def on_message(message):
        if message.content.startswith("bb! give"):
            args = message.content.split(" ")
            if args[1:][1] == "(my user ID)":
                global me
                global discordname
                me = me + int(args[1:][2])
                await client.send_message(message.channel, str(int(args[1:][2])) + "  brownie points have been given to " + str(discordname))
        if message.content.startswith("bb! brownies"):
            args = message.content.split(" ")
            if args[1:][1] == "(my user ID)":
                await client.send_message(message.channel, str(discordname) + " 
    currently has " + str(me) + " brownie points.")
    
    client.run(TOKEN)
    

    我想让机器人在每次用户加入服务器时创建一个新变量。然而,我尝试过的每一次尝试(即pickle模块、shelve模块…)导致以下后果之一:

    1. 它什么都不做
    2. It故障
    3. 它返回一个错误
    1 回复  |  直到 6 年前
        1
  •  0
  •   Patrick Haugh    6 年前

    为什么要导入 commands 如果您不使用扩展名?利用 命令 扩展并将代码从 on_message 事件这使您可以利用 命令 扩展,如 converters

    from discord.ext.commands import Bot
    import discord
    from collections import defaultdict
    
    bot = Bot('!')
    
    points = defaultdict(int)
    
    @bot.event
    async def on_ready():
        print("Ready")
    
    @bot.command(pass_context=True)
    async def give(ctx, member: discord.Member):
        points[member.id] += 1
        bot.say("{} now has {} points".format(member.mention, points[member.id]))
    
    @bot.command(pass_context=True)
    async def points(ctx, member: discord.Member):
        bot.say("{} has {} points".format(member.mention, points[member.id]))
    
    bot.run('token')
    

    至于持久化数据,您有几个选择。您可以将数据写入文件,然后将其读回,但我建议您考虑建立一个数据库。在其他地方和本网站上有大量的在线资源可以向您展示如何使用。如果您确实这样做了,那么您可能应该使用异步OUES数据库库,如 asyncpg