raise CommandInvokeError(exc) from exc, discord.py - discord

I'm new to python!
Errors in summary: CommandInvokeError(exc) from exc,ctx.command.invoke(ctx)
Here's my code.
#client.command(pass_context=True)
async def serverinfo(ctx):
embed = discord.Embed(name="{}'s info".format(ctx.message.guild.name), color=0x176cd5)
embed.add_field(name="guild Name", value=ctx.message.guild.name, inline=True)
embed.add_field(name="Roles", value=len(ctx.message.guild.roles), inline=True)
embed.add_field(name="Members", value=len(ctx.message.guild.members))
embed.add_field(name="Channels", value=len(ctx.message.guild.channels))
embed.add_field(name="Region", value=ctx.message.guild.region)
embed.add_field(name="Verification Level", value=ctx.message.guild.verification_level)
embed.add_field(name="Owner", value=ctx.message.guild.owner.mention)
embed.add_field(name="Emojis", value=len(ctx.message.guild.emojis))
embed.set_thumbnail(url=ctx.message.guild.icon_url)
embed.set_thumbnail(url=ctx.message.guild.icon_url)
embed.set_author(name=ctx.message.guild.name, icon_url=ctx.message.guild.icon_url)
embed.set_footer(text="Server ID is " + ctx.message.guild.id)
await ctx.send(embed=embed)
Error :-
File "C:\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
Can you help me to solve this?
Thanks!

I think you have added embed.set_thumbnail(url=ctx.message.guild.icon_url) 2 times remove one and try once again

Related

AttributeError: 'Context' object has no attribute 'guild_icon'

I am trying to set up a command to print the information of the server the bot is in. The code below gives the error AttributeError: 'Context' object has no attribute 'guild_icon'
#commands.command()
async def serverinfo(self,ctx):
name = str(ctx.guild.name)
description = str(ctx.guild.description)
owner = str(ctx.guild.owner)
id = str(ctx.guild.id)
region = str(ctx.guild.region)
memberCount = str(ctx.guild.member_count)
embed = discord.Embed(
title=name + " Server Information",
description=description,
color=discord.Color.blue()
)
embed.set_thumbnail(ctx.guild_icon)
embed.add_field(name="Owner", value=owner, inline=True)
embed.add_field(name="Server ID", value=id, inline=True)
embed.add_field(name="Region", value=region, inline=True)
embed.add_field(name="Member Count", value=memberCount, inline=True)
await ctx.send(embed=embed)
When trying to find the solution I tried to change the code to be
#commands.command()
async def serverinfo(self,ctx):
name = str(ctx.guild.name)
description = str(ctx.guild.description)
owner = str(ctx.guild.owner)
id = str(ctx.guild.id)
region = str(ctx.guild.region)
memberCount = str(ctx.guild.member_count)
embed = discord.Embed(
title=name + " Server Information",
description=description,
color=discord.Color.blue()
)
embed.set_thumbnail(ctx.guild.icon)
embed.add_field(name="Owner", value=owner, inline=True)
embed.add_field(name="Server ID", value=id, inline=True)
embed.add_field(name="Region", value=region, inline=True)
embed.add_field(name="Member Count", value=memberCount, inline=True)
await ctx.send(embed=embed)
But then I get the error discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: set_thumbnail() takes 1 positional argument but 2 were given
Could someone tell me what I have done wrong and point me in the right direction?
Problem 1
ctx.guild_icon does not exist, you fix this in your second code by using ctx.guild.icon
Problem 2
discord.Embed.set_thumbnail takes in a named argument for the image.
In fact, it doesn't take in an image at all, but rather a url
Solution
To solve your issue, you should use the following:
embed.set_thumbnail(url=ctx.guild.icon.url)
More info
discord.ext.commands.Context
discord.Embed.set_thumbnail

snipe command isn't mentioning user

I made a snipe command but the only problem is it doesn't mention a user properly. I've been trying to solve this for so long. I also attached a picture of what the snipe looks like.
Traceback Error:
Ignoring exception in command snipe:
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 "main.py", line 261, in snipe
embed = discord.Embed('description = f"<#!{snipe_message_author} deleted {snipe_message_content}')
TypeError: init() takes 1 positional argument but 2 were given
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: TypeError: init() takes 1 positional argument but 2 were given
smc = []
sma = []
snipe_message_content = None
snipe_message_author = None
snipe_message_id = None
#client.event
async def on_message_delete(message):
global snipe_message_content
global snipe_message_author
global snipe_message_id
snipe_message_content = message.content
snipe_message_author = message.author.id
snipe_message_id = message.id
await asyncio.sleep(60)
if message.id == snipe_message_id:
snipe_message_author = None
snipe_message_content = None
snipe_message_id = None
#client.command()
async def snipe(message):
if snipe_message_content==None:
await message.channel.send("Theres nothing to snipe.")
else:
embed = discord.Embed(description=f"{snipe_message_content}")
embed.set_footer(text=f"Asked by {message.author.name}#{message.author.discriminator}", icon_url=message.author.avatar_url)
embed.set_author(name= f"<#!{snipe_message_author}>")
await message.channel.send(embed=embed)
return
You can't mention users in the author field or the title field, better move it to the description.
embed = discord.Embed(description = f"<#!{snipe_message_author}> deleted `{snipe_message_content}`")

Is there an unban command that's working?

I've tried the following command:
#client.command
#commands.has_permissions(ban_members=True)
async def unban(ctx, *, member : discord.Member):
banned_users = await ctx.guild.bans()
member_name, member_disc = member.split("#")
for banned_entry in banned_users:
user = banned_entry.user
if(user.name, user.discriminator)==(member_name, member_disc):
await ctx.guild.unban(user)
unbanned = discord.Embed(title="Unban <:ban:756532045299318784>", description=f"**{member}** is unbanned! <a:tick:756202944461930567>", color=discord.Color.green(), timestamp=datetime.datetime.utcnow())
await ctx.send(embed = unbanned)
await ctx.send(f"Couldn't find **{member}** named person. iTs CaSe SeNsItIvE!")
Which is just a simple code to enter a name like "Wumpus#0001".
But it shows me up a big error:
Traceback (most recent call last):
File "C:\Users\Fujitsu\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 312, in _run_event
await coro(*args, **kwargs)
File "c:/Users/Fujitsu/Desktop/Yupiter/bot.py", line 40, in on_command_error
raise error
File "C:\Users\Fujitsu\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 903, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Fujitsu\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Fujitsu\AppData\Local\Programs\Python\Python38-32\lib\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: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
Ignoring exception in on_command_error
Traceback (most recent call last):
File "C:\Users\Fujitsu\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 312, in _run_event
await coro(*args, **kwargs)
File "c:/Users/Fujitsu/Desktop/Yupiter/bot.py", line 40, in on_command_error
raise error
discord.ext.commands.errors.CommandNotFound: Command "unban" is not found
"Command "unban" is not found".
What can I do, and is there a way to allow entering an ID instead of a username#discriminator?
You just made a simple mistake. #client.command must be #client.command().

Discord Error Loading JSON File: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

When i execute my code i receive next problem.Someone have a idea what i maked wrong in this code?
Ignoring exception in on_member_join
Traceback (most recent call last):
File "C:\Users\Adryan\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\client.py", line 270, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Adryan\Desktop\bot\cogs\events.py", line 51, in on_member_join
users = json.load(f)
File "C:\Users\Adryan\AppData\Local\Programs\Python\Python37\lib\json\__init__.py", line 296, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "C:\Users\Adryan\AppData\Local\Programs\Python\Python37\lib\json\__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "C:\Users\Adryan\AppData\Local\Programs\Python\Python37\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\Adryan\AppData\Local\Programs\Python\Python37\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
async def on_member_join(self, member):
with open('users.json', 'r') as f:
users = json.load(f)

Should Exception catch DeadlineExceededError exceptions?

I have the code like below:
try:
response = urlfetch.Fetch(url, deadline=60, headers=headers, follow_redirects=False)
except Exception, error_message:
logging.exception('Failed, exception happened - %s' % error_message)
but sometimes it fails with DeadlineExceededError? Should not this DeadlineExceededError be caught by my code?
The exception details:
Traceback (most recent call last):
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 266, in Handle
result = handler(dict(self._environ), self._StartResponse)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1529, in __call__
rv = self.router.dispatch(request, response)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1278, in default_dispatcher
return route.handler_adapter(request, response)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1102, in __call__
return handler.dispatch()
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 570, in dispatch
return method(*args, **kwargs)
File "/base/data/home/apps/s~myapp/1.375970700643773844/myapp.py", line 424, in get
url, response = call_api(origin=origin, destination=destination, date=date_.strftime('%Y-%m-%d'))
File "/base/data/home/apps/s~myapp/1.375970700643773844/myapp.py", line 288, in call_api
response = urlfetch.Fetch(url, deadline=60, headers=headers, follow_redirects=False)
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/api/urlfetch.py", line 270, in fetch
return rpc.get_result()
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/api/apiproxy_stub_map.py", line 612, in get_result
return self.__get_result_hook(self)
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/api/urlfetch.py", line 375, in _get_fetch_result
rpc.check_success()
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/api/apiproxy_stub_map.py", line 585, in check_success
self.__rpc, err)
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/api/apiproxy_stub_map.py", line 196, in Call
for key, function, srv, num_args in self.__content:
DeadlineExceededError
To answer your specific question, "Should not this DeadlineExceededError be caught by my code?":
The DeadlineExceededError class extends BaseException instead of Exception, so your except clause will never be called.
from google.appengine.runtime import DeadlineExceededError
my_error = DeadlineExceededError()
isinstance(my_error, Exception) # False
isinstance(my_error, BaseException) # True
First approach
Try excepting the DeadlineExceededError class by importing
from google.appengine.runtime import DeadlineExceededError and doing it like this:
try:
response = urlfetch.Fetch(url, deadline=60, headers=headers, follow_redirects=False)
except DeadlineExceededError, error_message:
logging.exception('Failed, exception happened - %s' % error_message)
Read more about it on the documentation.
Second Approach
I've faced this error before, and an approach I've followed was not to set which exception class I was trying to catch. I just called except.
try:
response = urlfetch.Fetch(url, deadline=60, headers=headers, follow_redirects=False)
except:
logging.exception('First failure')
# try again your request as suggested by the documentation
try:
response = urlfetch.Fetch(url, deadline=60, headers=headers, follow_redirects=False)
except:
logging.exception('Second failure')
return None
But I wasn't able to catch the error message, and instead of just logging an error message, I tried the request once again when the exception was raised, as the link I posted above suggests.
Some good links you should read
You should read this about Dealing with DeadlineExceedError.
There is also Backends, which allow you to avoid this request timer; with backends, there is no time limit for generating and returning a request.
Hope this helps you.

Resources