在discord.py中分别为每个用户更改变量

时间:2020-08-08 02:06:51

标签: python discord.py

我想存储一个整数“ money”并能够更改它,我是discord.py的新手

import discord
message.author.money = 100

client = discord.Client()

money = 100

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith('.hello'):
        await message.channel.send('Hello!')

    if message.content.startswith('.money'):
        await message.channel.send(message.author.money)
    
    if message.content,startswith('.addmoney'):
        message.author.money = message.author.money + 100

client.run('no')

此代码与不和谐联系在一起,但是键入'.addmoney'不会更改变量money。

2 个答案:

答案 0 :(得分:0)

Discord会在每条消息中创建 new 个用户对象。最好的选择是存储字典并使用用户ID。

import discord

client = discord.Client()

money = 100
data = {}

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    else:
        data.setdefault(message.author.id, money)

    if message.content.startswith('.hello'):
        await message.channel.send('Hello!')

    if message.content.startswith('.money'):
        await message.channel.send(str(data[message.author.id]))
    
    if message.content,startswith('.addmoney'):
        data[message.author.id] = data[message.author.id] + 100

client.run('no')

答案 1 :(得分:0)

如果是规模较小的事情,最好的方法是通过JSON

如果您尝试在python文件中执行此操作,则每次重新加载文件时,您的钱都会重置为您实现的默认值。

所以我的第一个建议是对JSON格式有一个基本的了解。 对于可以正常工作的基本代码示例,可能看起来像这样。

Import Discord
Import json
from discord.ext import commands

bot = discord.Client()

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------------------')

@client.event
async def on_message(message):
    if message.author.bot == False:
        with open('users.json', 'r') as f:
            users = json.load(f)

        await update_data(users, message.author)
        await add_cash(users, message.author)
 
    with open('users.json', 'w') as f:
         json.dump(users, f, indent=3)
    
    await client.process_commands(message)

async def update_data(users, user):
    if f'{user.id}' in users:
        return
    else:
        users[str(user.id)] = {}
        users[str(user.id)]['money'] = 0

此代码将检查用户是否在您的json文件夹中,如果不是,则将使用户成为用户,并分配货币值,每当他们写一条消息时,他们将获得5个“货币”。 / p>

要使此代码正常工作,您需要在bot目录中包含一个json文件,此外,您还需要在文件底部提供bot令牌以及bot.run(令牌)命令。

希望这很有道理。

相关问题