How can I access what the user passes in the command to use it the command error handler? discord.py - error-handling

How can I access what the user passes in the command user so I can use it the user.error handler?
here's what I've tried and didn't work:
#commands.command(aliases= ["info"])
async def user(self, ctx, *, member: discord.Member=None):
colors = [0xad1457, 0xe67e22, 0x992d22, 0x607d8b, 0x7289da, 0x71368a, 0x11806a]
if member == None:
embed = discord.Embed(color = random.choice(colors))
embed.add_field(name = "**Joined Discord**:", value = "`" + ctx.author.created_at.strftime("%d/%m/%Y %I:%M") + "`")
embed.add_field(name = "**Joined Server:**", value = "`" + ctx.author.joined_at.strftime("%d/%m/%Y %I:%M") + "`")
embed.set_footer(text = f"{ctx.author.name}")
embed.set_image(url = f"{ctx.author.avatar_url}")
await ctx.send(embed = embed)
else:
embed = discord.Embed(color = random.choice(colors))
embed.add_field(name = "**Joined Discord**:", value = "`" + member.created_at.strftime("%d/%m/%Y %I:%M") + "`")
embed.add_field(name = "**Joined Server:**", value = "`" + member.joined_at.strftime("%d/%m/%Y %I:%M") + "`")
embed.set_footer(text = f"{member.name}")
embed.set_image(url = f"{member.avatar_url}")
await ctx.send(embed = embed)
#user.error
async def user_error(self, ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send(f"**Wrong format. Use {ctx.prefix}user <user>**")
elif isinstance(error, commands.MemberNotFound):
await ctx.send(f"**πŸ™„ - {ctx.author.name}**, I can't find {member.id} in the server.")
else:
raise error
so I want to access what the user passes in the command so I can use it in the command handler.
and another question, how can I make the aliases doesn't need the prefix to run the command
example: in my code above I have info as aliases, I want if the user typed info(without the prefix) the bot will answer.

You can get the passed arguments and keyword arguments with ctx.args and ctx.kwargs.
EDIT:
#user.error
async def user_error(self, ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send(f"**Wrong format. Use {ctx.prefix}user <user>**")
elif isinstance(error, commands.MemberNotFound):
await ctx.send(f"**πŸ™„ - {ctx.author.name}**, I can't find a member with {error.argument} in the server.")
else:
raise error

Related

Telethon "DestroySessionRequest" method not work

I try destoy every new session.
I run main script, save all exist session to variable
all_session = await client(functions.account.GetAuthorizationsRequest())
hash_list = [x.hash for x in all_session.authorizations]
after i run and search for new session
if i got new session - i try destroy it
while True:
await asyncio.sleep(15)
all_new = await client(functions.account.GetAuthorizationsRequest())
new_hashes = [x.hash for x in all_new.authorizations]
for h in new_hashes:
if h not in hash_list:
logger.debug(f"have a new hash {h}")
try:
result = await client(functions.DestroySessionRequest(
session_id=-h
))
logger.debug(f"DROP RESULT IS: {result.stringify()}")
except Exception as e:
logger.debug(
f"error - {e}")
Every time then i try i got as response
DestroySessionNone(
session_id=3806172788422661047
)
i also tried use this method without "-", same result
try:
result = await client(functions.DestroySessionRequest(
session_id=-h
))
logger.debug(f"DROP RESULT IS: {result.stringify()}")
except Exception as e:
logger.debug(
f"error - {e}")

how to run an external function with variables from State?

this function must be run in the file where the bot is located
def start_pars():
from mainaio import data
username_input = driver.find_element(By.XPATH,
'/html/body/div/div/main/div/div/div/div[1]/form/div[1]/div[1]/div/input')
username_input.clear()
username_input.send_keys(data["username"])
pass_input = driver.find_element(By.XPATH,
'/html/body/div/div/main/div/div/div/div[1]/form/div[1]/div[2]/div/input')
pass_input.clear()
pass_input.send_keys(data["password"])
driver.find_element(By.XPATH, '/html/body/div/div/main/div/div/div/div[1]/form/div[2]/button').click()
time.sleep(1)
username1 = driver.find_element(By.XPATH, '/html/body/div[1]/nav[2]/div[2]/div/div[2]/div[2]/div')
print(username1.text)
less1 = []
lessundscore = driver.find_elements(By.XPATH, '/html/body/div[1]/div/main/div/div[2]/div/div[3]/div[1]')
for value in zip(lessundscore):
less1 += value
for val in less1:
print(val.text)
return username1, less1
items from the state must be transferred to the sending keys
class Registration(StatesGroup):
username = State()
password = State()
username = message.text
await state.update_data(username=username)
assword = message.text
await state.update_data(password=password)
data = await state.get_data()
I tried to run in the last registration function start_pars(data['username'], data['password'])

How can I use pandas.read_sql on an async connection?

I am trying to do the asynchron equivalent of
engine = create_engine('sqlite:///./test.db')
stmt = session.query(MyTable)
data = pd.read_sql(stmt, engine)
but it fails with the error AttributeError: 'AsyncConnection' object has no attribute 'cursor'.
What would be the right way to make this work?
asyn_engine = create_async_engine('sqlite+aiosqlite:///./test.db')
stmt = select(MyTable)
data = pd.read_sql(stmt, async_engine)
This code in principal is working...
# Making pd.read_sql connection the first argument to make it compatible
# with conn.run_syn()
def _read_sql(con, stmt):
return pd.read_sql(stmt, con)
async def get_df(stmt, engine):
async with engine.begin() as conn:
data = await conn.run_sync(_read_sql, stmt)
return data
asyn_engine = create_async_engine('sqlite+aiosqlite:///./test.db')
stmt = select(MyTable)
data = get_df(stmt, asyn_engine )

telethon how to request call with code for login

Since I am writing a client, my friends from the USA noticed that the code does not go through SMS, but only through a call. but I don’t understand how to do it, how to request a call(
await client.connect()
code_settings = types.CodeSettings(
current_number=True,
allow_flashcall=False,
allow_app_hash=False
)
result = await client(functions.auth.SendCodeRequest(
phone_number=phone,
api_id=api_id,
api_hash=api_hash,
settings=code_settings
))
# time.sleep(10)
result = await client(functions.auth.ResendCodeRequest(
phone_number=phone,
phone_code_hash=result.phone_code_hash
))
# time.sleep(20)
result = await client(functions.auth.ResendCodeRequest(
phone_number=phone,
phone_code_hash=result.phone_code_hash
))
# result = await client(SentCodeTypeCall(5))
# result = await client(functions.auth.)
while not isinstance(result.type, SentCodeTypeCall):
# time.sleep(10)
result = await client(functions.auth.ResendCodeRequest(
phone_number=phone,
phone_code_hash=result.phone_code_hash
))
# time.sleep(20)
# await client(functions.auth.SendCodeRequest(
# phone_number=phone,
# api_id=api_id,
# api_hash=api_hash,
# settings=code_settings
# ))
def code_callback():
code = input('Please enter the code you received: ')
return code
time.sleep(5)
await client.start(phone=phone, code_callback=code_callback)
I assume this is not the correct code.
can I tell the SendCode Request method to call immediately without sending SMS?

How can I know the command used? - Discord.py

I am trying to make a errorhandling for my Discord.py, how do I know what command was used for the error to pop up?
#bot.event
async def on_command_error(ctx, error):
print("error: ",error)
if search("not found", str(error)):
c_f = random.choice([f"`{command used}` was not found, silly.", "Ehm.. Since when do we have `{command used}`?", "I don't know what `{command used}` is?"])
embed=discord.Embed(title=c_f, description=f"Please use existing commands. {ctx.author.mention}", color=error_color)
embed.timestamp = datetime.utcnow()
embed.set_footer(text=bot_name, icon_url=icon_uri)
await ctx.send(embed=embed)
elif search("cooldown", str(error)):
c_d = random.choice(["Did you drink energy drinks!?", "Why are you stressing, buddy.", "Duhh, wait, you're on cooldown!"])
second_remain = round(error.retry_after, 1)
embed=discord.Embed(title=c_d, description=f"Try again after {second_remain}s. {ctx.author.mention}", color=error_color)
embed.timestamp = datetime.utcnow()
embed.set_footer(text=bot_name, icon_url=icon_uri)
await ctx.send(embed=embed)
else:
raise error
Any attribute I can use?
You can use ctx.command
#bot.event
async def on_command_error(ctx, exception):
error = getattr(exception, "original", exception)
if hasattr(ctx.command, "on_error"): # If a command has it's own handler
return
elif isinstance(error, CommandNotFound):
return
if isinstance(error, discord.CommandInvokeError):
print(ctx.command)
Your solution is to add them to the command specifically, this also means it can help diagnose an issue with a command more exact.
You can also add any error events to the specific listener, just like how you done it for all commands, instead add them individually.
#bot.command()
async def command_name(ctx):
# ...
#command_name.error
async def command_name_error(ctx, error):
if isinstance(error, commands.CommandInvokeError):
await ctx.send("An error from this command" + error)
With #command_name.error put your command name before the .error, then this makes an error listener for that command, if it produces an error.