Exception in thread Thread-2:
Traceback (most recent call last):
File "C:\Users\PC0\Anaconda3\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Users\PC0\Anaconda3\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "main_greetings.py", line 101, in between_callback
loop.run_until_complete(time_messege(args))
File "C:\Users\PC0\Anaconda3\lib\asyncio\base_events.py", line 616, in run_until_complete
return future.result()
File "C:\Users\PC0\Desktop\h ver 18-03\SmartBot-main\core\modules\greetings.py", line 6, in time_messege
bot = commands.Bot(command_prefix='.')
NameError: name 'commands' is not defined
我在提到 discord bot 时收到此错误,我不太清楚我做错了什么。这是我的那部分代码:
import time, random, discord
from datetime import datetime
async def time_messege(args):
bot = commands.Bot(command_prefix='.')
alarmtime = "16:26"
greeting_channel = bot.get_channel("814238156396298310")
#channel = bot.get_channel = xxx
while True:
lcltime = datetime.now().strftime('%H:%M')
if lcltime == alarmtime:
#aca pondria el code de detectar canal y enviar
print("is time!")
random_num = random.randint(1, 4)
if answer_num == 1:
await greeting_channel.send("Holi!, como estan chic@s?")
if answer_num == 2:
await greeting_channel.send("Holi!, Como va su dia? que me cuentan?")
if answer_num == 3:
await greeting_channel.send("Holi!, Como va su dia? que andan haciendo?")
elif answer_num == 4:
await greeting_channel.send("Holi!, como se encuentran?")
await time.sleep(90)
else:
print("not yet")
await time.sleep(10)
我在 main.py 中调用这个脚本:
import discord, json, os
import datetime, random, time
#Para poner mensajes por tiempo
from core.modules.greetings import time_messege
import threading
import asyncio
main_path = os.path.dirname(__file__)
""" Load Bot Configurations """
config_path = os.path.join(main_path, "config.json")
with open(config_path, "r") as jsonfile:
bot_config = json.load(jsonfile)
from core.smartbot import SmartBot
from core.modules.bot_brain import BotBrain
from core.modules.bot_actions import BotActions
bot_modules = [BotBrain, BotActions]
ChatBot = SmartBot(bot_config, bot_modules, main_path)
class BotClient(discord.Client):
@staticmethod
def is_DMChannel(message: str) -> bool:
"""Verifica si es un mensaje proveniente es de un canal privado"""
return isinstance(message.channel, discord.channel.DMChannel)
def save_log(self, response: str, message: object) -> None:
"""Guarda el historial de conversacion"""
date = datetime.datetime.now()
file_path = os.path.join(main_path, f"assets/log/{date.strftime('%d%b%y')}.txt")
with open(file_path, "a", encoding="utf-8") as text_file:
text_file.write(f"{message.content}\n{response}\n")
def load_content(self, name: str) -> dict:
"""Carga contenido .json de la carpeta embeds"""
embed_path = os.path.join(main_path, f"assets/embeds/{name}.json")
with open(embed_path, "r", encoding="utf-8") as jsonfile:
content = json.load(jsonfile)
return content
def create_embed(self, content: dict) -> object:
"""Crea un embed basado en el contenido de un diccionario"""
embed = discord.Embed(
title=content["title"],
description=content["description"],
color=int(content["color"], 16),
)
embed.set_thumbnail(url=content["icon_url"])
for key, value in content["content"].items():
embed.add_field(name=key, value=value, inline=content["inline"])
embed.set_footer(text=content["footer"])
return embed
def create_response(self, message: object) -> list:
"""Crea una respuesta en base al mensaje, y le da formato usando embeds"""
response = ChatBot(message.content, str(message.author.id))
if response != "#NoText":
embed_content = self.load_content("msg_container")
face_images = self.load_content("icon_urls")
state = ChatBot.user_data[str(message.author.id)]["state"]
if state in face_images:
embed_content["icon_url"] = face_images[state]
else:
embed_content["icon_url"] = random.choice(list(face_images.values()))
embed_content["description"] = f"`{response}`"
embed = self.create_embed(embed_content)
else:
embed = None
return response, embed
async def send_response(self, message: object, is_server=False) -> None:
"""Envia una respuesta por el canal de proveniencia del mensaje."""
response, embed = self.create_response(message)
if bot_config["DebugMode"]:
self.save_log(response, message)
print(f"{message.author}: {message.content}")
print(f"@ Bot: {response}")
if response and response != "#notext" and embed:
if is_server:
await message.reply(embed=embed)
else:
await message.channel.send(embed=embed)
def between_callback(self, args):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(time_messege(args))
loop.close()
#Ese metodo se ejecuta automaticamente cada vez que el bot se enciende
async def on_ready(self) -> None:
print("Logged on as {0}!".format(self.user))
#x = threading.Thread(target=time_messege) #Creo un thread independiente del main_thread
#x.start()
_thread = threading.Thread(target=self.between_callback, args=("some text", ))
_thread.start()
async def on_message(self, message: object) -> None:
if not message.author.bot:
if message.content.startswith(bot_config["prefix"]):
args = message.content.split(" ", 1)
command = args[0][len(bot_config["prefix"]):]
if command.lower() == "fit":
ChatBot.fit(args[1], str(message.author.id))
else:
if self.is_DMChannel(message):
await self.send_response(message)
elif not self.is_DMChannel(message) and self.user in message.mentions:
await self.send_response(message, is_server=True)
def ConsoleChat():
"""Permite utilizar al bot en la consola"""
fake_user = "Anonimous"
while True:
text = input("User >> ")
if text.lower() == "exit":
break
else:
response = ChatBot(text, fake_user)
if response != "#NoText":
print(f"Bot: {response}")
else:
print("*Parece que el bot no quiere responder*")
if __name__ == "__main__":
BotClient().run(bot_config["BotToken"]) #Online para Discord
#ConsoleChat() #Offline desde Consola
但是错误在类脚本中找到了
我应该以另一种方式引用机器人实例吗? 我该怎么办?
错误在于:bot = commands.Bot(command_prefix='.')
我导入了他们在评论中告诉我的内容,我至少可以迭代一次,因为它说“还没有”,虽然后来出现了这个错误,你怎么看?
Exception in thread Thread-2:
Trace (most recent recent calls):
File "C: \ Users \ PC0 \ Anaconda3 \ lib \ threading.py", line 932, in _bootstrap_inner
self.run ()
File "C: \ Users \ PC0 \ Anaconda3 \ lib \ threading.py", line 870, running
self._target (* self._args, ** self._kwargs)
File "main_greetings.py", line 101, in between_callback
loop.run_until_complete (time_messege (arguments))
File "C: \ Users \ PC0 \ Anaconda3 \ lib \ asyncio \ base_events.py", line 616, in run_until_complete
return future.result ()
File "C: \ Users \ PC0 \ Desktop \ h ver 18-03 \ SmartBot-main \ core \ modules \ greetings.py", line 36, at time_messege
sleep timeout (10)
TypeError: NoneType object cannot be used in 'await' expression
这是编辑过的代码,但它给出了等待错误
import time, random, discord
from datetime import datetime
from discord.ext import commands
async def time_messege(args):
bot = commands.Bot(command_prefix='.')
alarmtime = "9:01"
greeting_channel = bot.get_channel("814238156396298310")
#channel = bot.get_channel = xxx
while True:
lcltime = datetime.now().strftime('%H:%M')
if lcltime == alarmtime:
#aca pondria el code de detectar canal y enviar
print("is time!")
random_num = random.randint(1, 4)
if answer_num == 1:
await greeting_channel.send("Holi!, como estan chic@s?")
if answer_num == 2:
await greeting_channel.send("Holi!, Como va su dia? que me cuentan?")
if answer_num == 3:
await greeting_channel.send("Holi!, Como va su dia? que andan haciendo?")
elif answer_num == 4:
await greeting_channel.send("Holi!, como se encuentran?")
await time.sleep(90)
else:
print("not yet")
await time.sleep(10)
答案 0 :(得分:1)
只需导入它...
from discord.ext import commands
答案 1 :(得分:1)
您将机器人称为 commmands.Bot()
但你从未导入它
你只需要在开头输入 from discord.ext import commands
答案 2 :(得分:0)
对于您的第一个问题,您需要从 discord.ext 导入命令
您可以通过 from discord.ext import commands
对于你的第二个问题,
你不需要等待 time.sleep()
(这是你的错误所说的)
此外,time.sleep()
是同步的,会阻止整个机器人运行(阻塞)
改为使用异步的asyncio.sleep()
只需import asyncio
而不是 time.sleep(x) #x is number of seconds
使用 await asyncio.sleep(x)#x is number of seconds