Я пытаюсь выяснить, как инициировать прямое сообщение между игроком и ботом с помощью команд.Команда должна работать таким образом, чтобы DM игрока был ботом с! Stats и тремя числами (Пример:! Stats 6 8 1), и бот ответит соответствующим распределением статистики.(Пример: вы поставили 6 очков в Силе, 8 очков в Ловкости и 1 пункт в Телосложении.)
У меня есть следующий код:
import discord
from discord.ext import commands
import os
import json
from pathlib import Path
class Character(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_ready(self):
print("Bot is Online")
@commands.command()
async def name(self, ctx, name):
player = str(ctx.message.author)
path = os.getcwd()
charFolder = os.path.join(path + "/characters/")
charFile = Path(charFolder + player + ".txt")
# Get the name of character being created
if charFile.is_file():
await ctx.send("You've already created a character, dumbass.")
else:
await ctx.send("I did it!")
await ctx.send("Your character name is: " + name)
await ctx.send("Your character sheet has been created.")
levelDict = {1: [25, 1, 6, 15, 2, 1, 5, 75]}
characterFile = {}
level = 1
xp = 0
characterFile["name"] = name
characterFile["level"] = level
hp = levelDict[1][0]
characterFile["hp"] = hp
tFeats = levelDict[1][4]
characterFile["total feats"] = tFeats
numberOfDice = levelDict[1][1]
numberOfSides = levelDict[1][2]
characterFile["base damage"] = str(numberOfDice) + "d" + str(numberOfSides)
characterFile["hit"] = levelDict[1][5]
characterFile["damage"] = levelDict[1][5]
characterFile["ac"] = levelDict[1][6]
characterFile["currentxp"] = xp
nextLevel = levelDict[1][7]
characterFile["nextlevel"] = nextLevel
characterFile["strength"] = 0
characterFile["dexterity"] = 0
characterFile["constitution"] = 0
characterFile["remaining feats"] = 2
ap = levelDict[1][3]
characterFile["total ap"] = ap
hasTaken = []
characterFile["feats taken"] = hasTaken
file = open(charFolder + player + ".txt", "w", encoding="utf-8")
json.dump(characterFile, file, ensure_ascii=False, indent=2)
await ctx.send("PM me with '!stats <str> <dex> <con>' to set your abilities. Wouldn't want everyone "
"to see your secrets, would we?")
@commands.command()
async def stats(self, ctx, strength, dexterity, constitution):
private = self.client.send_message
player = str(ctx.message.author)
path = os.getcwd()
charFolder = os.path.join(path + "/characters/")
charFile = Path(charFolder + player + ".txt")
if not charFile.is_file():
await private(player, "You don't even have a character created yet. Type !name <name> in the room. "
"Where <name> is your character's actual name. (Example: !name Joe")
else:
strMod = int(int(strength) / 2)
dexMod = int(int(dexterity) / 2)
conMod = int(int(constitution) * 5)
print(strMod, dexMod, conMod)
await private(player, "Allocating the following: \n\n"
"Strength: " + strength + " (+" + str(strMod) + " bonus to hit and damage.)\n"
"Dexterity: " + dexterity + " (+" + str(dexMod) + " bonus to armor class.)\n"
"Constitution: " + constitution + " (+" + str(conMod) + " bonus to armor class.)\n")
BotCommands.py
import discord
import os
from discord.ext import commands
token = open("token.txt", "r").read()
client = commands.Bot(command_prefix = '!')
@client.command()
async def load(ctx, extension):
client.load_extension("cogs." + extension)
@client.command()
async def unload(ctx, extension):
client.unload_extension("cogs." + extension)
for filename in os.listdir("./cogs"):
if filename.endswith('.py'):
client.load_extension("cogs." + filename[:-3])
client.run(token)
Возвращает ошибку:
discord.ext.commands.errors.CommandInvokeError: Команда вызвала исключение: AttributeError: У объекта 'Bot' нет атрибута 'send_message'
Нужно ли инициировать какую-либо команду on_message в BotCommands.py?Или я просто вызываю метод неправильно?