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
I get this error when referring to the discord bot, I am not quite clear about what I am doing wrong. Here is my code for that part:
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)
And I call this script in the main.py with this:
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
But the error finds it in the class script
should I refer to the bot instance another way? What should I do with this?
The error is in: bot = commands.Bot(command_prefix='.')
I import what they told me in the comments, and I can at least iterate once because it said "not yet", although then this error appeared, what do you think?
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
This is the edited code but it give the error with await
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)
Simply import it...
from discord.ext import commands
You called the bot as commmands.Bot()
but you never imported it
you just have to type from discord.ext import commands
in the begining
For your first question, you need to import commands from discord.ext you can do this by from discord.ext import commands
For your second question, you don't need to await time.sleep()
(which is what your error says)
Also, time.sleep()
is synchronous and will stop the entire bot from function (blocking)
Instead, use asyncio.sleep()
which is asynchronous
simply import asyncio
and instead of time.sleep(x) #x is number of seconds
use await asyncio.sleep(x)#x is number of seconds
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.