snipe command isn't mentioning user - discord

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}`")

Related

How to send only 1 variable from a set of 3 in TinyDB

[DISCORD.PY and TINYDB]
I have set up a warning system for Discord. If someone gets warned, the data is saved like so:
{'userid': 264452325945376768, 'warnid': 37996302, 'reason': "some reason"}
Problem of this: I want the command "!warnings" to display these warnings, but I don't want it to have this ugly formatting of a JSON, instead I want it to display like so:
{member} has {amount} warnings.
WARN-ID: {warning id here}
REASON: {reason here}
To do this, I need to somehow call only one variable at a time instead of having all 3 (as of above JSON) instantly.
My code is as follows:
#Ralf.command()
async def warnings(ctx, *, member: discord.Member=None):
if member is None:
member = Ralf.get_user(ctx.author.id)
member_id = ctx.author.id
else:
member = Ralf.get_user(member.id)
member_id = member.id
WarnList = Query()
Result = warndb.search(WarnList.userid == member_id)
warnAmt = len(Result)
if warnAmt == 1:
await ctx.send(f"**{member}** has `{warnAmt}` warning.")
else:
await ctx.send(f"**{member}** has `{warnAmt}` warnings.")
for item in Result:
await ctx.send(item)
This code is working, but it shows the ugly {'userid': 264452325945376768, 'warnid': 37996302, 'reason': "some reason"} as output.
MAIN QUESTION: How do I call only userid without having warnid and reason displayed?
EDIT 1:
Trying to use dicts results in following:
For that I get the following:
Ignoring exception in command warnings:
Traceback (most recent call last):
File "C:\Users\entity2k3\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\entity2k3\Desktop\Discord Bots All\Entity2k3's Moderation\main.py", line 201, in warnings
await ctx.send(f"WARN-ID: `{Result['warnid']}` REASON: {Result['reason']}")
TypeError: list indices must be integers or slices, not str
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\entity2k3\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 903, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\entity2k3\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 859, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\entity2k3\AppData\Local\Programs\Python\Python39\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: TypeError: list indices must be integers or slices, not str
You are getting the TypeError because your Result is a list of dictionaries.
Make sure to iterate through Result and process each dictionary separately.
Your Result object is like this [{}, {}, {} ...]
Also you shouldn't capitalize the first letter of your variable. You should name it results, because it may contain more than 1 result.
for item in results:
user_id = item.get("userid")
warn_id = item.get("warnid")
reason = item.get("reason")
# do stuff with those

Problem with a setembed command (invalid literal for int() with base 10: '0x00ffff')

#commands.command()
async def setembed(self, ctx, title, link, footer, color, body):
emb = discord.Embed(title = f"{title}", description = f"{body}", color = color)
emb.set_footer(text=f"{footer}", icon_url = str(self.client.user.avatar_url))
emb.set_image(url=f"{link}")
await ctx.send(embed=emb)
So I was trying to make this command which allows users to set an embed in a channel they would like to, it takes the title, link, footer, and presumably body well too but when the user inputs a color, it gives the following error:
Traceback (most recent call last):
File "C:\Users\Aqua\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 467, in _actual_conversion
return converter(argument)
ValueError: invalid literal for int() with base 10: '0x00ffff'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Aqua\AppData\Local\Programs\Python\Python38\lib\site-packages\jishaku\cog_base.py", line 358, in jsk_debug
await alt_ctx.command.invoke(alt_ctx)
File "C:\Users\Aqua\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 856, in invoke
await self.prepare(ctx)
File "C:\Users\Aqua\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 790, in prepare
await self._parse_arguments(ctx)
File "C:\Users\Aqua\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 697, in _parse_arguments
transformed = await self.transform(ctx, param)
File "C:\Users\Aqua\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 552, in transform
return await self.do_conversion(ctx, converter, argument, param)
File "C:\Users\Aqua\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 505, in do_conversion
return await self._actual_conversion(ctx, converter, argument, param)
File "C:\Users\Aqua\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 476, in _actual_conversion
raise BadArgument('Converting to "{}" failed for parameter "{}".'.format(name, param.name)) from exc
discord.ext.commands.errors.BadArgument: Converting to "int" failed for parameter "color".
any idea why could this be? I do understand the error however not still sure how to fix it.
this is the user input:
r!setembed "This is the title" "https://nintendowire.com/wp-content/uploads/2020/09/Banner-SuperMario-3D-AllStars-Screenshot.jpg" "This is my footer" 0x00ffff "this is the body"
I did search for it however they were the cases where the value was a float value and users tried to convert it to int value directly so they rectified it by int(float(36.0000000))
36.0
Within a few minutes of asking this question, I stumbled upon a way to convert a hexadecimal string to hexadecimal int.
This is how I fixed the issue.
I just added this:
x = int(f"{color}", 16)
and then used the color in embed as x and now it works ^^

web2py, how to use fetch instead of urllib.request? (for GAE)

I'm starting a project that must be deployed at the Google App Engine. I read that gluon.tools fetch function must be used instead of urllib.request.
Here I have two defs(), the first one runs ok with urllib, the second one with fetch doesn't run.
It looks as if data parameters has the wrong format.
How must be used this fetch function?
I've been looking for examples along the internet but I don't find anything (except the code of fetchfunction).
# -*- coding: utf-8 -*-
from gluon.tools import fetch
import json
import urllib
def gQLquery1():
data = {'query':'{me{username myMachines{name}}}'}
url = 'https://ecostruxure-machine-advisor.se.app/daas/graphql'
Bearer = "Bearer ngU5TkM5yN2m5VCBeJBQ4F3NGjuvecn8FqK7f7Fc"
data = json.dumps(data).encode('utf-8')
headers={'authorization': Bearer,'Content-Type':'application/json'}
req = urllib.request.Request(url, data=data)
req.add_header('authorization', Bearer)
req.add_header('Content-Type', 'application/json')
response = urllib.request.urlopen(req).read()
decoded = json.loads(response)
out = json.dumps(decoded)
return out
def gQLquery2():
data = {'query':'{me{username myMachines{name}}}'}
url = 'https://ecostruxure-machine-advisor.se.app/daas/graphql'
Bearer = "Bearer ngU5TkM5yN2m5VCBeJBQ4F3NGjuvecn8FqK7f7Fc"
#data = json.dumps(data).encode('utf-8')
headers={'authorization': Bearer,'Content-Type':'application/json'}
#req = urllib.request.Request(url, data=data)
#req.add_header('authorization', Bearer)
#req.add_header('Content-Type', 'application/json')
#response = urllib.request.urlopen(req).read()
response = fetch(url, data , headers )
decoded = json.loads(response)
out = json.dumps(decoded)
return out
ticket returned:
Versión
web2py™ Version 2.21.1-stable+timestamp.2020.11.28.04.10.44
Python Python 3.7.4: D:\Oscar\_Particular\web2py\web2py_no_console.exe (prefix: D:\Oscar\_Particular\web2py)
Traceback (most recent call last):
File "D:\Oscar\_Particular\web2py\gluon\tools.py", line 4639, in fetch
from google.appengine.api import urlfetch
File "D:\Oscar\_Particular\web2py\gluon\custom_import.py", line 85, in custom_importer
return base_importer(pname, globals, locals, fromlist, level)
ModuleNotFoundError: No module named 'applications.hola'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:\Oscar\_Particular\web2py\gluon\restricted.py", line 219, in restricted
exec(ccode, environment)
File "D:/Oscar/_Particular/web2py/applications/hola/controllers/default.py", line 126, in <module>
File "D:\Oscar\_Particular\web2py\gluon\globals.py", line 430, in <lambda>
self._caller = lambda f: f()
File "D:/Oscar/_Particular/web2py/applications/hola/controllers/default.py", line 94, in gQLquery2
response = fetch(url, data , headers )
File "D:\Oscar\_Particular\web2py\gluon\tools.py", line 4642, in fetch
html = urlopen(req).read()
File "urllib\request.py", line 222, in urlopen
File "urllib\request.py", line 523, in open
File "urllib\request.py", line 1247, in do_request_
TypeError: POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str.

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().

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