【问题标题】:writing a bot for discord in python在 python 中编写一个不和谐的机器人
【发布时间】:2020-07-25 11:44:11
【问题描述】:

我有一个有效的货币系统,但我们想要赚钱的方法。所以我想做迷你游戏,所以我做了一个掷硬币的游戏,但我不能让它工作,它告诉我当我尝试它时找不到命令。我也想做它所以游戏成本>货币所以你可以赢一点,所以基本上投注

from discord.ext import commands
import discord
import json
import random
from discord.ext.commands import Bot
from discord import Game
import time
import asyncio
bot = commands.Bot('$')

amounts = {}

@bot.event
async def on_ready():
    global amounts
    try:
        with open('amounts.json') as f:
            amounts = json.load(f)
    except FileNotFoundError:
        print("Could not load amounts.json")
        amounts = {}

@bot.command(pass_context=True)
async def balance(ctx):
    id = str(ctx.message.author.id)
    if id in amounts:
        await ctx.send("You have {} :Ereb: in the bank".format(amounts[id]))
    else:
        await ctx.send("You do not have an account")

@bot.command(pass_context=True)
async def register(ctx):
    id = str(ctx.message.author.id)
    if id not in amounts:
        amounts[id] = 100
        await ctx.send("You are now registered")
        _save()
    else:
        await ctx.send("You already have an account")

@bot.command(pass_context=True)
async def transfer(ctx, amount: int, other: discord.Member):
    primary_id = str(ctx.message.author.id)
    other_id = str(other.id)
    if primary_id not in amounts:
        await ctx.send("You do not have an account")
    elif other_id not in amounts:
        await ctx.send("The other party does not have an account")
    elif amounts[primary_id] < amount:
        await ctx.send("You cannot afford this transaction")
    else:
        amounts[primary_id] -= amount
        amounts[other_id] += amount
        await ctx.send("Transaction complete")
    _save()

def _save():
    with open('amounts.json', 'w+') as f:
        json.dump(amounts, f)

@bot.command()
async def save():
    _save()

***@bot.command() #problem
async def on_message(message):
    if message.content.startswith('$coinflip'):
        randomlist = ["heads","tails",]
        await client.send_message(message.channel,(random.choice(randomlist)))***

bot.run("token")

    ```

【问题讨论】:

标签: python discord.py


【解决方案1】:

您需要使用bot.event 而不是bot.command 来装饰您的on_message 回调。您还需要添加bot.process_commands 行,以便正常调用其他命令。

@bot.event
async def on_message(message):
    if message.content.startswith('$coinflip'):
        randomlist = ["heads","tails",]
        await client.send_message(message.channel,(random.choice(randomlist)))
    else:
        await bot.process_commands(message)

【讨论】:

  • 我让它工作了,但它给出了两次正面或反面。
猜你喜欢
  • 2021-05-17
  • 2021-10-30
  • 2021-05-27
  • 2021-07-15
  • 2021-02-28
  • 2021-11-04
  • 2023-04-04
  • 1970-01-01
  • 2022-01-26
相关资源
最近更新 更多