Bug in Discord.py? - python

So I'm working on a cogs that can make my bot work as a modmail. So far, here's the code:
import discord
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
client = commands.Bot(command_prefix="!")
class Modmail(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.Cog.listener()
async def on_message(self, message):
empty_array = []
modmail_channel = discord.utils.get(message.guild.get_all_channels(), name="modmail")
if message.author == message.user:
return
if str(message.channel.type) == "private":
if message.attachments != empty_array:
files = message.attachments
await modmail_channel.send("<#" + message.author.id + ">: ")
for file in files:
await modmail_channel.send(file.url)
else:
await modmail_channel.send("<#" + str(message.author.id) + ">: " + message.content)
elif str(message.channel) == "modmail" and message.content.startswith("<"):
member_object = message.mentions[0]
if message.attachments != empty_array:
files = message.attachments
await member_object.send("**[MOD]** " + "**" + message.author.display_name + "**: ")
for file in files:
await member_object.send(file.url)
else:
index = message.content.index(" ")
string = message.content
mod_message = string[index:]
await member_object.send("**[MOD]** " + "**" + message.author.display_name + "**: " + mod_message)
def setup(bot):
bot.add_cog(Modmail(bot))
So the problem is, when I run it, I get this error:
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\Blue\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\Blue\Documents\Project\Articuno (Canary)\automod.py", line 39, in on_message
channel = discord.utils.get(guild.channels, name="📝║logs")
AttributeError: 'NoneType' object has no attribute 'channels'
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\Blue\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\Blue\Documents\Project\Articuno (Canary)\modmail.py", line 14, in on_message
modmail_channel = discord.utils.get(message.guild.get_all_channels(), name="modmail")
AttributeError: 'NoneType' object has no attribute 'get_all_channels'
What should I fix this? Because as far as I know, message and guild can't work together. But if I do message.get_all_channels(), it will have another error!

Related

AttributeError: module 'discord.ext.commands' has no attribute 'qualified_name' | Discord.py

I'm tryna make a help command. But when I run >help <cmd>
I get this error:
AttributeError: module 'discord.ext.commands' has no attribute 'qualified_name'
Here is the code:
class HelpCommand(commands.HelpCommand):
color = 0x171616
def footer(self):
return f"{self.clean_prefix}{self.invoked_with} <command> for more details"
def get_command_signature(self, command):
return f"```yaml\n{self.clean_prefix}{command.qualified_name} {command.signature}```"
async def send_cog_help(self, cog):
em = discord.Embed(
title=f"***{cog.qualified_name}** Commands", colour=self.color)
if cog.description:
em.description = cog.description
filtered = await self.filter_commands(cog.get_commmands(), sort=True)
for command in filtered:
em.add_field(name=command.qualified_name,
value=command.short_doc or "No Description Provided")
em.set_footer(text=self.footer())
await self.get_destination().send(embed=em)
async def send_command_help(self, command):
em = discord.Embed(title=command.qualified_name, color=self.color)
if command.help:
em.description = command.help
em.add_field(name="Syntax", value=self.get_command_signature(commands))
em.set_footer(text=self.footer())
await self.get_destination().send(embed=em)
async def send_bot_help(self, mapping):
em = discord.Embed(title="Loofah Help", color=self.color)
for cog, commands in mapping.items():
if not cog:
continue
filtered = await self.filter_commands(commands, sort=True)
if filtered:
value = "\t".join(f"`{i.name}`" for i in commands)
em.add_field(name=cog.qualified_name, value=value)
em.set_footer(text=self.footer())
await self.get_destination().send(embed=em)
Full traceback error:
Traceback (most recent call last):
File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\help.py", line 882, in command_callback
return await self.send_command_help(cmd)
File "D:\Kunnu\Loofah Rewrite\cogs\help.py", line 34, in send_command_help
em.add_field(name="Syntax", value=self.get_command_signature(commands))
File "D:\Kunnu\Loofah Rewrite\cogs\help.py", line 13, in get_command_signature
return f"```yaml\n{self.clean_prefix}{command.qualified_name} {command.signature}```"
AttributeError: module 'discord.ext.commands' has no attribute 'qualified_name'
Any help is appreciated

AttributeError: 'NoneType' object has no attribute 'get_role' 'send' or 'members'

I'm getting the same error multiple times for a program and I can't find what the issue is; I keep getting the same error
_ClientEventTask exception was never retrieved
future: <ClientEventTask state=finished event=on_ready coro=<bound method Mod.on_ready of <lib.cogs.mod.Mod object at 0x000001B219E2BBE0>> exception=AttributeError("'NoneType' object has no attribute 'send'")>
Traceback (most recent call last):
File "C:\Users\jacob\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Projects\BobbyBot\lib\cogs\mod.py", line 278, in on_ready
self.mute_role = self.bot.guild.get_role(653941858128494600)
AttributeError: 'NoneType' object has no attribute 'get_role'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\jacob\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 348, in _run_event
await self.on_error(event_name, *args, **kwargs)
File "c:\Projects\BobbyBot\lib\bot\__init__.py", line 125, in on_error
await self.stdout.send("An error occured.")
AttributeError: 'NoneType' object has no attribute 'send'
_ClientEventTask exception was never retrieved
future: <ClientEventTask state=finished event=on_ready coro=<bound method Reactions.on_ready of <lib.cogs.reactions.Reactions object at 0x000001B219ECC7C0>> exception=AttributeError("'NoneType' object has no attribute 'send'")>
Traceback (most recent call last):
File "C:\Users\jacob\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Projects\BobbyBot\lib\cogs\reactions.py", line 27, in on_ready
"\u2764\ufe0f": self.bot.guild.get_role(653940117680947232), # Red
AttributeError: 'NoneType' object has no attribute 'get_role'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\jacob\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 348, in _run_event
await self.on_error(event_name, *args, **kwargs)
File "c:\Projects\BobbyBot\lib\bot\__init__.py", line 125, in on_error
await self.stdout.send("An error occured.")
AttributeError: 'NoneType' object has no attribute 'send'
Here is the main document of which everything is based:
from asyncio import sleep
from datetime import datetime
from glob import glob
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.cron import CronTrigger
from discord import Embed, File, DMChannel, Intents
from discord.errors import HTTPException, Forbidden
from discord.ext.commands import Bot as BotBase
from discord.ext.commands import Context
from discord.ext.commands import (CommandNotFound, BadArgument, MissingRequiredArgument,
CommandOnCooldown)
from discord.ext.commands import when_mentioned_or, command, has_permissions
from ..db import db
OWNER_IDS = [213438742315139073]
COGS = [path.split("\\")[-1][:-3] for path in glob("./lib/cogs/*.py")]
IGNORE_EXCEPTIONS = (CommandNotFound, BadArgument)
def get_prefix(bot, message):
prefix = db.field(
"SELECT Prefix FROM guilds WHERE GuildID = ?", message.guild.id)
return when_mentioned_or(prefix)(bot, message)
class Ready(object):
def __init__(self):
for cog in COGS:
setattr(self, cog, False)
def ready_up(self, cog):
setattr(self, cog, True)
print(f" {cog} cog ready")
def all_ready(self):
return all([getattr(self, cog) for cog in COGS])
class Bot(BotBase):
def __init__(self):
self.ready = False
self.cogs_ready = Ready()
self.guild = None
self.scheduler = AsyncIOScheduler()
try:
with open("./data/banlist.txt", "r", encoding="utf-8") as f:
self.banlist = [int(line.strip()) for line in f.readlines()]
except FileNotFoundError:
self.banlist = []
db.autosave(self.scheduler)
super().__init__(
command_prefix=get_prefix,
owner_ids=OWNER_IDS,
intents=Intents.all()
)
def setup(self):
for cog in COGS:
self.load_extension(f"lib.cogs.{cog}")
print(f" {cog} cog loaded")
print("setup complete")
def update_db(self):
db.multiexec("INSERT OR IGNORE INTO guilds (GuildID) VALUES (?)",
((guild.id,) for guild in self.guilds))
db.multiexec("INSERT OR IGNORE INTO exp (UserID) VALUES (?)",
((member.id,) for member in self.guild.members if not member.bot))
to_remove = []
stored_members = db.column("SELECT UserID FROM exp")
for id_ in stored_members:
if not self.guild.get_member(id_):
to_remove.append(id_)
db.multiexec("DELETE FROM exp WHERE UserID = ?",
((id_,) for id_ in to_remove))
db.commit()
def run(self, version):
self.VERSION = version
print("running setup...")
self.setup()
with open("./lib/bot/token.0", "r", encoding="utf-8") as tf:
self.TOKEN = tf.read()
print("running bot...")
super().run(self.TOKEN, reconnect=True)
async def process_commands(self, message):
ctx = await self.get_context(message, cls=Context)
if ctx.command is not None and ctx.guild is not None:
if message.author.id in self.banlist:
await ctx.send("You are banned from using commands.")
elif not self.ready:
await ctx.send("I'm not ready to receive commands. Please wait a few seconds.")
else:
await self.invoke(ctx)
async def rules_reminder(self):
await self.stdout.send("Remember to adhere to the rules!")
async def on_connect(self):
print(" bot connected")
async def on_disconnect(self):
print("bot disconnected")
async def on_error(self, err, *args, **kwargs):
if err == "on_command_error":
await args[0].send("Something went wrong.")
await self.stdout.send("An error occured.")
raise
async def on_command_error(self, ctx, exc):
if any([isinstance(exc, error) for error in IGNORE_EXCEPTIONS]):
pass
elif isinstance(exc, MissingRequiredArgument):
await ctx.send("One or more required arguments are missing.")
elif isinstance(exc, CommandOnCooldown):
await ctx.send(f"That command is on {str(exc.cooldown.type).split('.')[-1]} cooldown. Try again in {exc.retry_after:,.2f} secs.")
elif hasattr(exc, "original"):
# if isinstance(exc.original, HTTPException):
# await ctx.send("Unable to send message.")
if isinstance(exc.original, Forbidden):
await ctx.send("I do not have permission to do that.")
else:
raise exc.original
else:
raise exc
async def on_ready(self):
if not self.ready:
self.stdout = self.get_channel(759434903145152533)
self.scheduler.add_job(self.rules_reminder, CronTrigger(
day_of_week=0, hour=12, minute=0, second=0))
self.scheduler.start()
self.update_db()
embed = Embed(title="Now Online",
description="Bobby Bot is now online.", timestamp=datetime.utcnow())
fields = [("Name", "Bobby Bot", True),
("Latency", str(round(bot.latency * 1000)) + "ms", True)]
for name, value, inline in fields:
embed.add_field(name=name, value=value, inline=inline)
embed.set_author(name="Bobby Bot", icon_url="https://cdn.discordapp.com/attachments/794376573213736991/887527732228018276/Bobbys.png")
embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/794376573213736991/887527732228018276/Bobbys.png")
await self.stdout.send(embed=embed)
while not self.cogs_ready.all_ready():
await sleep(0.5)
await self.stdout.send("Now online!")
self.ready = True
print(" bot ready")
meta = self.get_cog("Meta")
await meta.set()
else:
print("bot reconnected")
async def on_message(self, message):
if not message.author.bot:
if isinstance(message.channel, DMChannel):
if len(message.content) < 50:
await message.channel.send("Your message should be at least 50 characters in length.")
else:
member = self.guild.get_member(message.author.id)
embed = Embed(title="Modmail",
colour=member.colour,
timestamp=datetime.utcnow())
embed.set_thumbnail(url=member.avatar_url)
fields = [("Member", member.display_name, False),
("Message", message.content, False)]
for name, value, inline in fields:
embed.add_field(name=name, value=value, inline=inline)
mod = self.get_cog("Mod")
await mod.log_channel.send(embed=embed)
await message.channel.send("Message relayed to moderators.")
else:
await self.process_commands(message)
bot = Bot()
No matter what I try it keeps coming up with the same error regardless of the fact that I know I followed the vid tutorial I was going through exactly. I can't find why it's not recognising self
self.guild is None
You defined self.guild as None and that's the reason why you get the NoneType error. The self.guild should be a guild object I think, but it isn't. None has no attributes like get_role() or something, because its empty and not a discord guild.
self.stdout doesn't exist
I read your code and can't find it anywhere. Because its not in your code, you can't use it as variable, you need to define it.

Trying to get the number of warns a users has and send it discord.py

I get a new error now. I edited smth now and i get this error. What to do. New code is given below
#commands.command()
async def warn(self, ctx, user:discord.Member, *, reason=None):
user_id = user.id
if collection.count_documents({"userid":user.id}) == 0:
collection.insert_one({"userid":user.id,"count":0})
if reason == None:
return await ctx.send("Please mention a reason!")
elif user == None:
return await ctx.send("Please mention a member!")
user = collection.find_one({"userid":user.id})
current_count = user["count"]
new_count = current_count + 1
collection.update_one({"userid":user.id}, {"$set": {"count": new_count}})
em = discord.Embed(title = "Member Warned!", description = f"Warned {user.mention} for **{reason}** | They now have {new_count} warnings!", timestamp = ctx.message.created_at, color = 0xFF0000)
em.set_footer(text=f'Warned By {ctx.author} | ID: {ctx.author.id}', icon_url = ctx.author.avatar_url)
await ctx.send(embed = em)``` This is the code
Ignoring exception in command warn:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/runner/HorribleSentimentalParallelprocessing/cogs/warn.py", line 30, in warn
collection.update_one({"userid":user.id}, {"$set": {"count": new_count}})
AttributeError: 'dict' object has no attribute 'id'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'dict' object has no attribute 'id'```
You are trying to find the user without any warnings. You were also adding warnings to the author himself instead of the user.
#commands.command()
async def warn(self, ctx,user: discord.Member, *,reason=None):
if collection.count_documents({"userid":user.id}) == 0:
collection.insert_one({"userid":user.id,"count":0})
if reason is None:
return await ctx.send("Please mention a reason!")
user_doc = collection.find_one({"userid":user.id})
current_count = user_doc["count"]
new_count = current_count + 1
collection.update_one({"userid":user.id}, {"$set": {"count": new_count}})
em = discord.Embed(title = "Member Warned!", description = f"Warned {user.mention} for **{reason}** | They now have {new_count} warnings!", timestamp = ctx.message.created_at, color = 0xFF0000)
em.set_footer(text=f'Warned By {ctx.author} | ID: {ctx.author.id}')
collection.update_one({"userid":ctx.author.id}, {"$inc": {"count": 1}})
await ctx.send(embed = em)

Opening a specific file with Python but an error occurred

I am currently trying to make my discord.py bot opening the specific file: {guild.id}_config.yaml, here is my following code:
for guild in self.bot.guilds:
if guild.get_member(before.id) is None:
continue
else:
def get_channel_id():
with open(f'configuration/{guild.id}_config.yaml', 'r') as id_accessor:
ID = yaml.safe_load(id_accessor)
id_string: discord.TextChannel = guild.get_channel(ID['plugins']['logging']['type']['member_log']['channel'])
return id_string
MemberLoggingChannel = get_channel_id()
if before.avatar != after.avatar:
AvatarEmbed = discord.Embed(title=f":pencil: {before.name} Changed His/Her Avatar", colour=0xa6f7ff)
AvatarEmbed.set_thumbnail(url=after.avatar_url)
await MemberLoggingChannel.send(embed=AvatarEmbed)
elif before.name != after.name:
NameEmbed = discord.Embed(title=f":pencil: {after.name} Changed His/Her Username", colour=0xa6f7ff)
NameEmbed.add_field(name="Before", value=f"{before.name}", inline=True)
NameEmbed.add_field(name="After", value=f"{after.name}", inline=False)
await MemberLoggingChannel.send(embed=NameEmbed)
elif before.discriminator != after.discriminator:
DiscriminatorEmbed = discord.Embed(title=f":pencil: {after.name} Changed His/Her Username", colour=0xa6f7ff)
DiscriminatorEmbed.add_field(name="Before", value=f"{before.discriminator}", inline=True)
DiscriminatorEmbed.add_field(name="After", value=f"{after.discriminator}", inline=False)
await MemberLoggingChannel.send(embed=DiscriminatorEmbed)
But for some reason the guild id isn't in the connected guilds of my bot. Here is the list of connected guild IDs:
631100984176672768
650736030319771674
613660252545613834
And the error looks like so:
Ignoring exception in on_user_update
Traceback (most recent call last):
File "whatever file path", line 312, in _run_event
await coro(*args, **kwargs)
File "whatever file path", line 111, in on_user_update
MemberLoggingChannel = get_channel_id()
File "whatever file path", line 104, in get_channel_id
with open(f'configuration/{guild.id}_config.yaml', 'r') as id_accessor:
FileNotFoundError: [Errno 2] No such file or directory: 'configuration/613660252545613834_config.yaml'
How can I fix the problem, and what am I wrong here?

Guess my number minigame per discord bot with discord.py

I am trying to code a discord bot with python.
I wanted to include this minigame, where I can guess a random number (within 7 tries, that's what the for loop is for). But I get errors, which I can't detect in the code. I honestly think, it's from wrong commands, but I can't know.
I wrote the following code as clear as possible (I think so).
#name of file: Experimental Drone 5
import random
import discord
from discord.ext import commands
from discord.ext.commands import Bot
import asyncio
drone = commands.Bot(command_prefix="!")
[...]
#drone.command(pass_context=True)
async def chat(ctx):
#drone.event
async def on_message(message):
[...]
elif message.content.startswith("guess number"): #line 54
await drone.send_message(message.channel, "text")
z = random.randint(1, 100)
for gT in range(1, 8):
await drone.say("Guess it!") #line 58
g = await drone.wait_for_message(int)
if g > z:
await drone.send_message(message.channel, "text")
elif g < z:
await drone.send_message(message.channel, "text")
else:
break
if g == z:
await drone.send_message(message.channel, "text")
else:
await drone.send_message(message.channel, "text. My number was
actually " + str(z)) #line 69
Errors: (username changed)
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\name\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\discord\client.py", line 307, in _run_event
yield from getattr(self, event)(*args, **kwargs)
File "C:\Users\name\Desktop\Trustworthy Drones\Experimental Drone
5\Experimental Drone 5 .py", line 58, in on_message
await drone.say("Guess it!")
File "C:\Users\name\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\discord\ext\commands\bot.py", line 309, in _augmented_msg
msg = yield from coro
File "C:\Users\name\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\discord\client.py", line 1145, in send_message
channel_id, guild_id = yield from self._resolve_destination(destination)
File "C:\Users\name\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\discord\client.py", line 289, in _resolve_destination
raise InvalidArgument(fmt.format(destination))
discord.errors.InvalidArgument: Destination must be Channel, PrivateChannel,
User, or Object. Received NoneType

Categories