I'm trying to add roles to users by listening for Reaction. Although it will succeed, there will always be errors after execution. I want to ask how to solve this problem?
Codes there:
#client.event
async def on_raw_reaction_add(payload: discord.RawReactionActionEvent):
if payload.message_id == 0000:
guild: discord.Guild = client.get_guild(payload.guild_id)
if payload.emoji.name == "someEmoji":
role0: discord.Role = guild.get_role(1111)
await payload.member.add_roles(role0)
elif payload.emoji.name == "someEmoji":
role1: discord.Role = guild.get_role(2222)
await payload.member.add_roles(role1)
Logs(With pysnooper):
19:50:26.101973 line 54 await member.add_roles(role1)
19:50:26.104641 return 54 await member.add_roles(role1)
Return value:.. <Future pending>
Starting var:.. payload = <RawReactionActionEvent message_id=1111...d=None> event_type='' member=None>
Starting var:.. guild = <Guild id=1111 name='' shard_id=0 chunked=True member_count=0>
Starting var:.. member = <Member id=00000 name='member'>
Starting var:.. role1 = <Role id=11111 name='role1'>
19:50:26.588117 call 54 await member.add_roles(role1)
19:50:26.590784 exception 54 await member.add_roles(role1)
Exception:..... StopIteration
[2022-12-20 19:50:26] [ERROR ] discord.client: Ignoring exception in on_raw_reaction_remove
Traceback (most recent call last):
File "C:\Users\****\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "main.py", line 54, in on_raw_reaction_remove
await member.remove_roles(en_role)
File "C:\Users\****\AppData\Local\Programs\Python\Python38\lib\site-packages\pysnooper\tracer.py", line 367, in __exit__
start_time = self.start_times.pop(calling_frame)
KeyError: <frame at 0x000001A1014E6DD0, file 'main.py', line 54, code on_raw_reaction_remove>
This line of code
await channel.edit(user_limit=0, name="💤|Dormant", overwrites=discord.PermissionOverwrite(read_messages = False))
Sourcing from
elif before.channel is not None and after.channel is None: # User left a channel
channel = before.channel
if len(channel.members) == 0:
print("debug 3")
if str(channel.name).startswith("Currently"):
print("debug 4")
await channel.edit(user_limit=0, name=":zzz:|Dormant", overwrites=discord.PermissionOverwrite(read_messages = False))
await asyncio.sleep(600)
await channel.edit(name="Waiting for game to be played...", roles=None, reason="The voice channel was empty")
await channel.set_permissions(role=discord.Role.name())
Returns
AttributeError: 'PermissionOverwrite' object has no attribute 'items'
Sourcing from
Ignoring exception in on_voice_state_update
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "z:\Programming\Python\Discord Bots\Channel name changer\main.py", line 37, in on_voice_state_update
await channel.edit(user_limit=0, name="💤|Dormant", overwrites=discord.PermissionOverwrite(read_messages = False))
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\channel.py", line 733, in edit
await self._edit(options, reason=reason)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\abc.py", line 289, in _edit
for target, perm in overwrites.items():
AttributeError: 'PermissionOverwrite' object has no attribute 'items'
Why does it return that error, and what in the code needs to be addressed for it to function properly?
If you want the overwrite to apply to everyone, you need to use the #everyone role for set_permissions.
await channel.set_permissions(
ctx.guild.default_role, # applies it to #everyone of the guild
overwrite=discord.PermissionOverwrite(read_messages=False)
)
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.
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)
I'm trying to make a Reaction Role bot with the ability to set the role given when reacted. I have tried:
verifyroleid = int(0)
#bot.command(pass_context=True)
#has_permissions(administrator=True)
async def set(ctx, *, roleid=None):
em = discord.Embed(title="yBot | VERIFY")
em.add_field(name="SUCCESS: ",value="Set {} as 'verify' role!".format(roleid))
em.set_footer(text="© 2020 - Powered by yanuu ;k#2137")
verifyroleid == roleid
await ctx.send(embed=em)
#bot.command(pass_context=True)
async def verify(ctx):
em = discord.Embed(title="yBOT | VERIFY")
em.add_field(name="REACT: ", value="React '✅' to this message to get verified!", inline=False)
em.set_footer(text="© 2020 - Powered by yanuu ;k#2137")
message = await ctx.send(embed=em)
await message.add_reaction("✅")
reaction, user = await bot.wait_for("reaction_add")
def check(reaction, user):
return user != bot.user and str(reaction.emoji) in ["✅"]
while True:
try:
reaction, user = await bot.wait_for("reaction_add")
if str(reaction.emoji) == "✅":
await message.remove_reaction(reaction, user)
role = discord.utils.get(ctx.guild.roles, id=verifyroleid)
await discord.Member.add_roles(user, role)
except asyncio.TimeoutError:
await message.delete()
return
But it results in an error:
Traceback (most recent call last):
File "C:\Users\macio\AppData\Roaming\Python\Python38\site-packages\discord\client.py", line 333, in _run_event
await coro(*args, **kwargs)
File "C:\Users<..>\Documents\pythontest\diskord-test.py", line 99, in on_command_error
raise error
File "C:\Users<..>\AppData\Roaming\Python\Python38\site-packages\discord\ext\commands\bot.py", line 903, in invoke
await ctx.command.invoke(ctx)
File "C:\Users<..>\AppData\Roaming\Python\Python38\site-packages\discord\ext\commands\core.py", line 859, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users<..>\AppData\Roaming\Python\Python38\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: 'NoneType' object has no attribute 'id'
How can I fix this?