#discord-bots

1 messages · Page 1151 of 1

smoky marsh
#

damnw hat does that mean

sick birch
warped mirage
#

``py

#
@client.command()
@commands.has_permissions(ban_members = True)
async def unban(ctx, member : discord.Member):
        try:
            await ctx.send(f"{member.name} has been unbanned.")
        except: 
            await ctx.reply("The user you are trying to unban is not banned.")
        await ctx.guild.unban()```
#

doesnt work and no errors , any ideas?

warped mirage
#

for required arguments only

sick birch
#

Can I see the error handler?

warped mirage
#
@client.event
async def on_command_error(ctx, error: Exception):

    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.reply(f'Please specify a username.', delete_after = 10)```
sick birch
#

Is that everything?

warped mirage
#

yes

sick birch
#

Oo that seems like a bad idea

smoky marsh
sick birch
#

Currently it's going to silently ignore all errors that aren't commands.MissingRequiredArgument

#

You can fix it by re-raising the error using raise error

warped mirage
#

can u help me please then

hardy yoke
#

the gist explained all that lol

warped mirage
#

nope

#
@client.event
async def on_command_error(ctx, error: Exception):

    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.reply(f'Please specify a username.', delete_after = 10)

        raise error``` like this?
sick birch
smoky marsh
#

Ah okay

sick birch
sick birch
#

You unindented it too far

#

It needs to be inside of the error handler but outside of the if statement

warped mirage
#
@client.event
async def on_command_error(ctx, error: Exception):

    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.reply(f'Please specify a username.', delete_after = 10)

    raise error
        ``` can be like this?
sick birch
#

That's perfect

warped mirage
#

ok

sick birch
#

Now run the unban command again, and it should tell you what the error is

warped mirage
#
discord.ext.commands.errors.MemberNotFound: Member "@brandon08" not found.```
#

how can i unban , i wanna do it by the id if possible?

#
@client.command()
@commands.has_permissions(ban_members = True)
async def unban(ctx, member : discord.Member):
        try:
            await ctx.send(f"{member.name} has been unbanned.")
        except: 
            await ctx.reply("The user you are trying to unban is not banned.")
        await ctx.guild.unban()```
sick birch
#

Doing it by ID should be possible

warped mirage
#

doesnt work

cold sonnet
#

should be doable with a discord.utils.get through guild.bans

warped mirage
#

how can i do that

cold sonnet
#

await ctx.guild.unban(discord.utils.get(await ctx.guild.bans(), id=id))

#

if I didn't miss something

warped mirage
#

discord.ext.commands.errors.MemberNotFound: Member "940304995960643634" not found.

#

still no

cold sonnet
#

I need the full code please

warped mirage
#
@client.command()
@commands.has_permissions(ban_members = True)
async def unban(ctx, member : discord.Member):
        try:
            await ctx.send(f"{member.name} has been unbanned.")
        except: 
            await ctx.reply("The user you are trying to unban is not banned.")
        await ctx.guild.unban(discord.utils.get(await ctx.guild.bans(), id=id))```
cold sonnet
#

well I thought we wanna do it by id

#

how are you gonna convert a user that's not in the server to a discord.Member

#

a discord.Member is in a server

warped mirage
#

oh so what should i do

cold sonnet
#

I suggest converting member to an int

#

then
await ctx.guild.unban(discord.utils.get(await ctx.guild.bans(), id=member))

paper sluice
#

you can use get_user or fetch_user to get a discord.User object which you can use to unban

cold sonnet
#

does the bot have access to the user

paper sluice
#

they do.

sick birch
#

@warped mirage if the user is banned, they're probably not a discord.Member, so try typehinting to discord.User instead

slate swan
#

anyone know how fix?

warped mirage
# sick birch <@944343972258648115> if the user is banned, they're probably not a `discord.Mem...

it worked but py File "C:\Users\Program\Desktop\Bot\main.py", line 33, in on_command_error raise error File "C:\Users\Program\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1330, in invoke await ctx.command.invoke(ctx) File "C:\Users\Program\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 995, in invoke await injected(*ctx.args, **ctx.kwargs) # type: ignore File "C:\Users\Program\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 209, in wrapped raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: object async_generator can't be used in 'await' expression it works but sends errors still, can i do smth to keep this clean

cold sonnet
slate swan
slate swan
hardy yoke
#

they're called context menu commands, what library are you using (discord.py)?

cold sonnet
#
await ctx.guild.unban(discord.utils.get(bans, id=member))
cold sonnet
#

or if you have converted to discord.User already

#

and it does provide a User instance

warped mirage
#

ye i did discord.User, btw will this work for multiguild

cold sonnet
#

then you can just pass that instance to unban

hardy yoke
#

go to line 19

#

and that's an example for both a user context menu command (right click username > apps) or a message context command

warped mirage
cold sonnet
#

it's gonna work in the guild you use the command in

whole sparrow
#

how do i run a concurrent task next to bot.run in main.py

warped mirage
#

so if a user is already banned it returns a message, or user is already unbanned message

cold sonnet
#

why not convert to discord.Member and it's gonna show an error if the guy isn't in the guild

#

wait I'm dumb

#

that's not the same

warped mirage
#

Yh

#

And I need it as a message, not on terminal

cold sonnet
#

if user in (await ctx.guild.bans())?

cold sonnet
#

you can handle errors

warped mirage
#

Idk how ig

slate swan
#

im trying to build a discord bot that looks up an IP addr from a text file and creates an embed with the returned data however this is extremely slow whats the best way to multithread/pool this without breaking the bot

paper sluice
slate swan
#

i have 20k ips to lookup btw so yh

paper sluice
sick birch
slate swan
#

no external apis used

#

if i print the data its fine but soon as i put data into an embed it takes years

cold sonnet
slate swan
#

i was thinking if i did a function inside my command that did the lookup and for ip in ips asyncio.run that function but idk if that will work/be stable

slate swan
devout iris
#

Hia

#

I want to make a music command, which api should i use?

#

Is there an api for that?

exotic maple
#

How do i run some code after a user has reacted to a message in DMS?

slate swan
#

discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body In name: String value did not match validation regex.

#

im trying to create custom emoji with discord py

#

i got that error when i did await guild.create_custom_emoji(name="emojione", image=img.read())

visual island
sick birch
cloud dawn
cerulean folio
#

Hi guys !
My bot is receiving this message saying i'm being rate limited. The docs about it are really overwhelming me. It's been two weeks I'm running away from that task but now I have to face it. Can you just... cheer me up a bit and guide me through it please? pleadingmelt

cloud dawn
#

What are you doing?

cerulean folio
#

wdym?

slate swan
#

anyone willing to work on an advance discord bot along with an official site and optional web panels for server moderation etc

using discord.py

slate swan
slate swan
sick birch
slate swan
#

this does not break the bot or the new thread. i use this for other things on my bot

sick birch
slate swan
#

i was replying to this mainly

#

threading will break the bot process then restart once the thread is over or sometimes wont even start back up for a while

slate swan
glossy shore
#

hello
is it possible to establish a websocket connection and have a discord bot interact with this connection (send & receive data)
and make it do some things based on the received data ?

slate swan
#

yes @glossy shore. The socket server or client must be threaded

glossy shore
#

i'm making a simple class that would handle the sending and receiving of data
using the websockets module
i've been using asyncio for a while but event loops and background tasks are new to me honestly ...

slate swan
#

you can also use aiohttp to handle the gateway and to make requests to the RESTAPI

glossy shore
#

i'll first clean up my code and either send it here or in a help channel
to get some insight on how can integrate with discord.py

dusky pine
cerulean folio
sick birch
#

Well there you have it then

pliant gulch
#

Wouldn't a hundred requests a minute be totally fine

#

The global ratelimit is 50/1s

#

Are you hosting on some shared VPS?

pliant gulch
slate swan
#

once you send a good amount of request per second. you'll DOSIng the server

cerulean folio
hardy yoke
# cerulean folio I do

it's not your fault then, it's because repl shares IP's with loads of other bots

Type kill 1 in repl's shell and it'll usually fix it but it'll happen from time to time unless you get your own host

sick birch
cerulean folio
#

wait how can the host be responsible of a discord rate limit?

#

the host is just a machine that'll run the same program

slate swan
hardy yoke
#

because the host has, say, 1000 bots all on the same ip making requests to discord

pliant gulch
slate swan
#

O_o, thats not gonnah do much?

hardy yoke
#

eventually discord says no thank you and blocks the ip

slate swan
#

whats kill 1 in repl shell?

cerulean folio
#

oh... I see...

#

aight

dusky pine
#

kill the process with PID 1 iirc

slate swan
#

.........

pliant gulch
#

Yea and that causes the process manager repl.it uses under the hood to spawn a new enviourment

slate swan
#

killing the process is suppose to stop IP Block from cloudflare? LOL

hardy yoke
#

yes it kills your session and more often than not will also put you on a new server/ip therefore fixing the problem

slate swan
cerulean folio
#

i gotta learn how to host a bot on another cloud platfom then x.x

cloud dawn
slate swan
#

what does killing your procces have to do with stopping IP Block from CF lmfao

sweet geyser
#

You probably will regret it

slate swan
#

eh, doubt it

pliant gulch
dusky pine
#

just buy a VPS, simple solution

slate swan
cerulean folio
sweet geyser
slate swan
#

repl is where all the rookies are lol. most likely all IP blocked from CF

cerulean folio
#

a rocket wdym?

hardy yoke
#

repl causing rate limit bans has been an issue for years this isn't a new or unique problem, and kill 1 has always been the (temp) fix

dusky pine
#

A VPS is on the cloud bro

slate swan
#

dude what, are you good

#

LMAO lmfao

#

im legit dying rn

#

did u not see the cloudflare page?

cloud dawn
dusky pine
#

discord is the one that has CF

cerulean folio
slate swan
#

it isnt a repl error with the rate limit.........

sweet geyser
slate swan
slate swan
#

idk what module he using

sweet geyser
dusky pine
slate swan
#

wait wait

hardy yoke
pliant gulch
dusky pine
#

wait, that's not bootstrap

slate swan
#

dude

cerulean folio
#

thing that i like with replit is that when you close the site and open it again you see all the console activity from when you weren't on the website if that makes sense

#

i don't know how to do this on virtual machine

dusky pine
#

~/.bash_history

sweet geyser
pliant gulch
#

You could use logging module as well

slate swan
#

bro even if u ban the IP on discord end. it should reply blocked or some error code

sweet geyser
#

I use arch btw

slate swan
#

not CF

sick birch
dusky pine
slate swan
#

CF and discord API are different, unless they added rate limiting on CF aswell

dusky pine
#

i think zsh has zsh_history too

pliant gulch
slate swan
#

you can have rate limiting on both API and CF

pliant gulch
#

Discord API uses CF 😄 that's why it's given

slate swan
#

CF panel is a whole different thing

sweet geyser
pliant gulch
#

Uhh, ok? But discord API does indeed use CF

dusky pine
pliant gulch
#

It's utilising CF

slate swan
#

bro lmfao

#

i was ppl would learn

sweet geyser
slate swan
#

i've been using CF for so long, i dnt get that

pliant gulch
sweet geyser
#

Bash is the basic component

slate swan
#

unless i set it

cerulean folio
pliant gulch
# pliant gulch

As you can see here ^ Discord API is using CF, isn't that crazy?

hardy yoke
#

qol = quality of life

sweet geyser
#

@slate swan Please explain what you are trying to do

pliant gulch
#

It's almost like, all the APIs used now a day use CF for ddos protection, and metics

slate swan
#

Discord rate limiting system is source code wise. not CF panels

cerulean folio
#

typically i'll create a VM on google cloud and host the bot on it, then ssh into the VM

#

but then i'll just find an empty console

pliant gulch
dusky pine
#

fork bash and make that feature kekw

sweet geyser
#

Well here is how to solve it run it through docker

sick birch
cerulean folio
sweet geyser
#

Or use screen

slate swan
#

CF is in between

pliant gulch
#

Yes... so discord API uses CF??

sweet geyser
#

Yes

cerulean folio
hardy yoke
#

I don't see the relevance of this debate it's bordering off topic

#

They were given a cause and solution

#

Nuff said innit

cerulean folio
slate swan
#

do you know the different between IP Banning checking IP in source code and blocking IP in CF panels under "security/rules"

sweet geyser
dusky pine
cloud dawn
sweet geyser
#

Very light weight

#

@cerulean folio I'm willing to help you with that

pliant gulch
cerulean folio
#

so that's just been made for console history?

cerulean folio
pliant gulch
#

Okay, show me the part in their codebase regarding this

sweet geyser
#

Afaik there are no cons

#

I'll send more info on dm

slate swan
#

ok so here i got 2 options, i can either go in my source code and check for IPs that are blacklisted or use CF to block incoming IP like this below

https://puu.sh/JbsLx/a0907bf26d.png

#

@pliant gulch

pliant gulch
#

Does discord use your source code? My question was regarding their codebase

#

😄

slate swan
#

i HIGHLY doubt discord uses any of CF settings. CF is mainly used to protect backend IP

#

with rate limiting, you should be good on DDOS attacks.

#

DDOSing is just a shit ton of request per second. i do it and work on related stuff for it lol

pliant gulch
unkempt canyonBOT
#

discord/http.py lines 102 to 111

async def json_or_text(response: aiohttp.ClientResponse) -> Union[Dict[str, Any], str]:
    text = await response.text(encoding='utf-8')
    try:
        if response.headers['content-type'] == 'application/json':
            return utils._from_json(text)
    except KeyError:
        # Thanks Cloudflare
        pass

    return text```
unkempt canyonBOT
#

discord/http.py lines 467 to 469

if not response.headers.get('Via') or isinstance(data, str):
    # Banned by Cloudflare more than likely.
    raise HTTPException(response, data)```
pliant gulch
#

Crazy

slate swan
#

whats that suppose to mean?

#

all you doing is confirming what im saying lol.......

#

there no proof of discord using CF settings lol

spark raptor
#

a little help someone?

slate swan
spark raptor
#

apparently commands isn't part of discord.ext?

pliant gulch
slate swan
#

lol

#

making sure

slate swan
#

twice

spark raptor
#

oh

hardy yoke
#

import discord.ext < delete

cloud dawn
spark raptor
#

still doesn't work

cloud dawn
#

py-cord has a different structure you need to follow.

spark raptor
#

ok

cloud dawn
#

No clue just know it's py-cord stuff lol

hardy yoke
#

I read they're rewriting pycord from the ground up
"deforking" it

pliant gulch
hardy yoke
#

Yeah it made me raise an eyebrow but good luck 2 them lol

cloud dawn
#

They could make some improvements, sure but they would need a dedicated small team.

pliant gulch
#

I take one look at a file in pycord, there is a method with no return type, sandwiched in-between two other methods that BOTH have a return type
Mostly a nit-pick but, typing is all-or-nothing imo 😔

spark raptor
#

maybe I should just

#

make something that isn't a discord bot for now

hardy yoke
spark raptor
#

ok, do you have any suggestions on what to do?

hardy yoke
#

🤷‍♂️ my first project was an IRC bot years back pre-discord. I remember it was difficult at the time but I persisted with it.

there's some good lists of "beginner projects" on reddit if you search around a bit

spark raptor
#

o k

sweet geyser
#

My suggestion is to learn a bit about the api

pliant gulch
old gate
#

Hey I need some help with posting to an api would anyone be able to help me

#

My response.post just wont seem to work on my python bot

#

I have an api for reporting scam numbers and none seem to want to push through.

#

anyone awake ? lol

cloud dawn
#

This is the discord api sir

old gate
#

No its a private api with a company

#

Its for busting and turning scammers into the authories

cloud dawn
#

Meant this channel

old gate
#

Oh i am sorry

#

I didn't realise its for that api only

acoustic summit
#

since discord.py support has been cut, i uninstalled and installed py-cord but now none of my commands work
the bot goes online and everything but no commands do anything
i just did pip uninstall discord.py, is that incorrect?

cloud dawn
acoustic summit
#

yeah but discord cut support for it no?

#

thats why it doesnt have buttons n whatnot?

cloud dawn
#

It does have buttons

acoustic summit
#

oh what

cloud dawn
#

I think you still have the old version installed 1.7.3

acoustic summit
#

can you link me somewhere i can learn how to use them?

#

maybe

dusky pine
#

discord doesn't provide support to libraries, discord has its own independent api that the libraries connect to

old gate
#

What server supports external api's

#

Cause its just a simple responce.post command

acoustic summit
dusky pine
dusky pine
#

not a server but eh

cloud dawn
#

Then head over to the docs and switch it from stable to latest

#

In the repo there are also examples of buttons under view

dusky pine
#

pip install git+https://github.com/Rapptz/discord.py

#

latest version

#

and i think ashley has a tutorial on how to use message components

slate swan
#

thats for app commands

#

but you can find plenty in the examples folder of discord.py repo

acoustic summit
#

tyty <3

robust fulcrum
#

Code jam overed?

slate swan
slate swan
slate swan
#
await interaction.followup.edit_message(embed=e23,view=self)

i want to edit the embed which i sent through the command

dusky pine
#

show the full error

#

the message button is blocking it

slate swan
slate swan
#

wait

#

idk

visual island
#

how "idk"?

#

anyways, I've tried the exact code and worked fine

#

and usually, that error pops up when you are trying to register an app command with an invalid name

slate swan
#
from helpbot import Dropdown,Dropdown2
Traceback (most recent call last):
  File "c:/Users/hp/Desktop/bot/main.py", line 50, in <module>
    bot.load_extension("helpbot")
  File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\disnake\ext\commands\common_bot_base.py", line 487, in load_extension
    self._load_from_module_spec(spec, name)
  File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\disnake\ext\commands\common_bot_base.py", line 419, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
disnake.ext.commands.errors.ExtensionFailed: Extension 'helpbot' raised an error: ImportError: cannot import name 'Dropdown' from 'helpbot' (c:\Users\hp\Desktop\bot\helpbot.py)

what's the problem? why cant i import

slate swan
#

i think i have problem in that

visual island
slate swan
#

hbday @visual island :D 🥳

visual island
#
await guild.create_custom_emoji(name="emojione", image=open("img.png", "rb").read())
``` something like this
visual island
slate swan
#

Okay

robust fulcrum
slate swan
#
with open(filet, "wb") as file:
          file.write(requests.get(u).content)
        with open(filet, "rb") as ig:
          jmh = bytearray(ig.read())
          print("d")
          try:
            await guild.create_custom_emoji(name=f"emotes{randh}{h}{i}{randh}", image=open(filet, "rb").read())
          except Exception as hh:
            print(hh)
robust fulcrum
visual island
slate swan
#

i have a channel where there are emojies, and i get emojies from that channel and put it in a file and then put them in bot

#

then delete the file

visual island
slate swan
#

oh

slate swan
slate swan
#

@visual island hbd NM_PeepoBlushHat

visual island
#

are you using an app command?

slate swan
#

a task

slate swan
#

is it because of filet

#

filet is just a name of the file

visual island
#

okay, do you have any app commands then?

slate swan
slate swan
#

bot.command?

visual island
slate swan
#

no i don't have any

visual island
#

!d discord.app_commands.command

unkempt canyonBOT
#

@discord.app_commands.command(*, name=..., description=..., nsfw=False, extras=...)```
Creates an application command from a regular function.
slate swan
#

i don't have

visual island
#

hmm

#

okay, what's this: requests.get(u).content

#

what's u in particular?

slate swan
#

emoji url

visual island
#

why do you need that?

slate swan
slate swan
visual island
#

you can't have / in emoji names

slate swan
#

Oh

visual island
#

that was the issue from the beginning 🙂

slate swan
#

i removed it still the same error

visual island
#

and dot

slate swan
#

ooh

#

why discord is so strict

#

it works :D

#

the solution was so easy i wasted an hour trying to fix the image thing 💀

dusky pine
#

not necessarily strict, just match regex and done

slate swan
#

i don't know wwhats regex

visual island
#

string pattern matching stuff

slate swan
#

ooohhh

slate swan
shrewd apex
#

yeah

#

as long as u are good at regex there is no string u can't parse except html tags

slate swan
#

nice

robust fulcrum
#

I bored
I wana make a comand but have no good idea

slate swan
robust fulcrum
dusky pine
slate swan
robust fulcrum
dusky pine
robust fulcrum
#

Ye

dusky pine
#

the one like everyone can use

robust fulcrum
#

Ye

slate swan
robust fulcrum
#

I have that

robust fulcrum
dusky pine
robust fulcrum
#

What?

#

And i have one question

#

I have filled the form for the perspective api but they have not sent me email from 1 week is there any possible reason?

daring olive
robust fulcrum
shrewd apex
#

just type none or student

shrewd apex
robust fulcrum
daring olive
#

yeah we zap forms links bc of people posting surveys

shrewd apex
#

oh i c

shrewd apex
robust fulcrum
#

Done!

robust fulcrum
vale wing
#

With aiohttp

#

Idk how you gotta provide the key to their API but in most of google APIs it goes as a param so

await session.get("...", params={"key": "your_api_key"})  #pseudocode```
vale wing
vocal snow
#

wow

shrewd apex
#

🥲

vocal plover
#

No I have that link in my alt's dms because it's possibly the greatest stackoverflow post of all time

#

or at least, the top comment is

shrewd apex
#

0-0

#

i see edited my comment

#

Viewed 3.4m times 0-0

vocal plover
#

yeah it's uh, pretty famous lmao

scarlet sorrel
#

How do i make a simple bot that starts when i do a command, then starts counting up from 1 (sending each number in the channel as it goes) until it sees another command?

wanton cipher
#
# command 1
run = True
num = 0
while run:
  num += 1

# command 2
run = False
scarlet sorrel
#

Ill try

wanton cipher
scarlet sorrel
#

I dont think it will

#

It will never get to the 2nd command

wanton cipher
#

oh yeah, this too xD

scarlet sorrel
#

For sending messages in a loop? Why would that ban it lol that aint how it works

wanton cipher
#

spam I think

scarlet sorrel
#

Iv had a bot in a loop sending messages for months now

#

Yea nah dude, iv had one going for months

#

You have to make alot more api calls then that

#

1 per second is nothing

wanton cipher
#

ngl... I can kinda agree with the 1 per second thing as I've done tons of loops and they worked now that I think about it 🤔

scarlet sorrel
#

...

#

Do u know what await message is lol

vocal plover
#

With how ratelimiting works in most Discord libs each iteration will just happen as soon as the ratelimit bucket is refreshed or isn't empty

shrewd apex
#

the ratelimits are dynamic so no sure shot way of saying if u get banned or not

scarlet sorrel
shrewd apex
#

huh?

vocal plover
#

I think they're referring to Messageable.send(), which will wait for the ratelimits before making a request, thus meaning you never get blocked

shrewd apex
#

how is a coroutine related to ratelimits if coro stopped rate limits then why would rate limits exist

scarlet sorrel
#

Have you ever made a bot im so confused

shrewd apex
#

no let's just take a simple example

vocal plover
#

what?

shrewd apex
#

say i do client presence change every 1 second like u are saying

vocal plover
#

That's not how the API's ratelimiting works

shrewd apex
#

i am doing await as well that dosent change the fact i get rate limited

vocal plover
#

the only time an unrelated route will get you blocked is if:

  • you exceed the global limit
  • you get banned by cloudflare due to 10k 4XX requests in 10 minutes
scarlet sorrel
#

I just want a cancelable loop

vocal plover
#

You could have some sort of variable, say "stop" which is initialised to False when you run the count command. Each iteration of the loop you check if that value is True, and if so break out of the loop. In your stop counting command you just have to set "stop" to True

vocal plover
#

yeah, precisely that

sigh

wanton cipher
#

xD

slate swan
#
bot = commands.Bot(...)


@tasks.loop(seconds=1)
async def mes(channel: discord.TextChannel):
  await channel.send("uwu")

@bot.command()
async def uwu(ctx: commands.Context) -> None:
  mes.start(ctx.channel)

@bot.command()
async def not_uwu(ctx: commands.Context) -> None:
  mes.cancel()

pepeShy

#

why use a while loop when you can use a task loop

wanton cipher
#

fair

visual island
#

do you think the command is triggered?

vale wing
#
  1. Use aiosqlite
#

Blocking

#
  1. You need to have only one connection
visual island
#

how do you know?

vale wing
#
  1. member = member or ctx.author
visual island
#
  1. Don't use f-string for the sql query
vale wing
#
  1. except IndexError
#

That is that

visual island
#

There are some possible issues, for example not having process_commands() in the on_message event or you didn't enable message_content intent

vocal plover
#

Actual explanations because just pointing out a bunch of shit doesn't help anyone:

  1. aiosqlite doesn't block the event loop while making queries, since discord bots are inherently asynchronous this means you can have multiple of a command running at once
  2. using or in this way will return the first truthy object, a non-None member is truthy, failing that it will fall back to ctx.author
  3. f-strings for SQL queries can lead to SQL injection, allowing people to make malicious queries. while this wont be an issue for a member id specifically, it's a good practice not to use
  4. it's important to catch named exception types, otherwise you could hide a different type of exception which makes debugging hell
vale wing
#
  1. use this
cur.execute("SELECT wallet, bank FROM main WHERE user_id = ?", (member.id,))```
slate swan
#

waiting for 2

vocal plover
#

2 is a statement, you dont need more than one connection, there's nothing more to say, you just dont

vale wing
#
  1. Creating a connection is an expensive procedure, you can just have one connection and create own cursor for each operation, it is better to have an execute method somewhere in bot class for everything rather than creating new connection and cursor every time you want to make a query
kind trellis
#

How do I remove a slash command that is not in my code? I had it as part of my group thing, when trying to get figure out how slash commands work, and now it doesn't delete on re-sync

slate swan
#

what library

kind trellis
#

I've been trying for hours and it won't delete itself

vale wing
#

Last time I faced this issue I ended up making raw requests for each command to delete

kind trellis
kind trellis
slate swan
#

just use this ```py
import asyncio
import hikari

rest = hikari.RESTApp()

TOKEN =
GUILD_ID = hikari.UNDEFINED

async def main():
async with rest.acquire(TOKEN, hikari.TokenType.BOT) as client:
application = await client.fetch_application()

    await client.set_application_commands(application.id, (), guild=GUILD_ID)

asyncio.run(main())

dusky pine
#

sarth they said dpy

slate swan
#

just a quick code to purge all commands

dusky pine
#

why would you want an extra library for that

slate swan
dusky pine
#

a ic

warped mirage
#

guys i need help

warped mirage
#
discord.app_commands.errors.CommandInvokeError: Command 'mute' raised an exception: HTTPException: 400 Bad Request (error code: 50007): Cannot send messages to this user``` can someone help me make a error function so if the bot cant dm someone does as a reply ig
slate swan
dusky pine
slate swan
#

and place your token there

#

run it and done.

kind trellis
vale wing
#
from requests import put
put(f"https://discord.com/api/v10/applications/{your_bot_id}/commands", json=[], headers={"Authorization": "Bot " + token})```
This should delete all commands tho idk ^
slate swan
#

that seems like more of your python config settings....

visual island
kind trellis
#

Can I just resync locally?

vale wing
slate swan
#

i think you need to fetch the commands first, im unsure

vale wing
slate swan
warped mirage
#

can someone help me?

vale wing
#

Empty list would just delete them

#

At least I think so

slate swan
#

yeah it should work then

warped mirage
# slate swan what's the issue

discord.app_commands.errors.CommandInvokeError: Command 'mute' raised an exception: HTTPException: 400 Bad Request (error code: 50007): Cannot send messages to this user i need to make a error function for this,

warped mirage
slate swan
#

!try-except

#
try:
    await user.send(...)
except:
    # unable to send message
warped mirage
#
@client.event
async def on_command_error(ctx, error: Exception):

    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.reply(f'Please specify a user or ID to complete this command', delete_after = 10)

    raise error``` i have this, can i add another error thing here
vale wing
#

!e py try: 50 / 0 except ZeroDivisionError: print("Can't divide by zero")

slate swan
#

you can catch the specific error using ```py
except discord.Forbidden:
...

#

buttons? cat_tf

warped mirage
vale wing
#

3.11

unkempt canyonBOT
#

@vale wing :white_check_mark: Your eval job has completed with return code 0.

Can't divide by zero
warped mirage
hazy oxide
warped mirage
vale wing
#

Forbidden inherits from HTTPException iirc

slate swan
#

yes, and is specific to 403 status

warped mirage
#

well i need to add the error thing for like 3 commands

slate swan
#

;-; create a helper function to send dms then maybe..

warped mirage
#
@client.command(description="Mute the specified user")
@commands.has_permissions(ban_members=True)
async def mute(ctx, member: discord.Member, *, reason=None):
    guild = ctx.guild
    mutedRole = discord.utils.get(guild.roles, name="muted")

    if not mutedRole:
        mutedRole = await guild.create_role(name="muted")

        for channel in guild.channels:
            await channel.set_permissions(mutedRole, speak=False, send_messages=False)
    await member.add_roles(mutedRole, reason=reason)
    await ctx.send(f"{member.mention} has been muted for {reason}")
    await member.send(f"You have been muted in {guild.name} for {reason}")``` how would i do it here
vale wing
#

try-except is basic python

#

Wrap your critical statement (send) into it and there ya go

warped mirage
#

.. ok then nvm

stray carbon
#
def is_manager():
        async def predicate(ctx: commands.Context):
            async with ctx.bot.server_db.cursor() as cursor:
                await cursor.execute("SELECT manager FROM donation_setup WHERE guild = ?", (ctx.guild.id,))
                data = await cursor.fetchone()
                role = ctx.guild.get_role(data[0]) if data else None     
                if role:
                    if role in ctx.author.roles:
                        return True
                    elif ctx.author.guild_permissions.manage_guild is True:
                        return True
                    else:
                        embed = discord.Embed(color=0xe74c3c)
                        embed.description = ':PinkWarn: User with **Manage Server** permissions or **Donations Manager** role have access to this command.'
                        await ctx.reply(embed=embed, view=DeleteView(ctx))
                        return False
                else:
                    if ctx.author.guild_permissions.manage_guild is True:
                        return True
                    else:
                        embed = discord.Embed(color=0xe74c3c)
                        embed.description = ':PinkWarn: User with **Manage Server** permissions or **Donations Manager** role have access to this command.'
                        await ctx.reply(embed=embed, view=DeleteView(ctx))
                        return False
        return commands.check(predicate) 

https://media.discordapp.net/attachments/967355402016677918/998175645303586826/unknown.png?width=620&height=441

isnt there any way to ignore the check for help command

warped mirage
#
@client.command(description="Mute the specified user")
@commands.has_permissions(ban_members=True)
async def mute(ctx, member: discord.Member, *, reason=None):
    guild = ctx.guild
    mutedRole = discord.utils.get(guild.roles, name="muted")

    if not mutedRole:
        mutedRole = await guild.create_role(name="muted")

        for channel in guild.channels:
            await channel.set_permissions(mutedRole, speak=False, send_messages=False)
    await member.add_roles(mutedRole, reason=reason)
    await ctx.send(f"{member.mention} has been muted for {reason}")
    await member.send(f"You have been muted in {guild.name} for {reason}")
    if not member.send:
        try: 
            await ctx.send("This cannot be done")
        except:
            await ctx.reply("This has worked")
``` will this work?
slate swan
stray carbon
slate swan
#

in the check

kind trellis
vale wing
#

That thing didn't work?

slate swan
kind trellis
#

It worked, but it only removed the global command

slate swan
#

oh

warped mirage
#

can someone help me?

slate swan
#

use this then

vale wing
#

Then this

from requests import put
put(f"https://discord.com/api/v10/applications/{your_bot_id}/guilds/{guild_id}/commands", json=[], headers={"Authorization": "Bot " + token})```
warped mirage
#
@client.command(description="Mute the specified user")
@commands.has_permissions(ban_members=True)
async def mute(ctx, member: discord.Member, *, reason=None):
    guild = ctx.guild
    mutedRole = discord.utils.get(guild.roles, name="muted")

    if not mutedRole:
        mutedRole = await guild.create_role(name="muted")

        for channel in guild.channels:
            await channel.set_permissions(mutedRole, speak=False, send_messages=False)
    await member.add_roles(mutedRole, reason=reason)
    await ctx.send(f"{member.mention} has been muted for {reason}")
    await member.send(f"You have been muted in {guild.name} for {reason}")
    if not member.send:
        try: 
            await ctx.send("This cannot be done")
        except:
            await ctx.reply("This has worked")
``` will this work?
kind trellis
#

How would that be done?

vale wing
#

Server settings -> interactions -> your bot app -> edit stuff

#

You can predefine it in code I think but I never tried

#

Those are called permissions v2 or smth

warped mirage
#

.

vale wing
#

Not ctx.send

warped mirage
#

what then

vale wing
#

You need to provide values to embed fields

#

Good

kind trellis
vale wing
#

Ok gl

warped mirage
#

lol to fix my thing its impossible then

vale wing
kind trellis
#

It sucked that Windows forced me to update when I was in the middle of de-bugging

#

I got booted off the internet and had no choice but to restart my computer and let it install updates

warped mirage
vale wing
#

Not to offend but the questions you ask make me think you just found some yt tutorial on "how to make a discord bot" and copypasted the code from there

#

Sorry if this is wrong but like fr @warped mirage

kind trellis
#

That looks like before the rewrite was done

vale wing
#

Not you lol

warped mirage
#

And even so that doesn’t fix the dm error

vale wing
#

f"{message_before.content}" is a useless str cast, content is already a str and in the future cast to str with str(obj)

vale wing
#

Not knowing it is weird

#

That's just bad practice

#

Brb

warped mirage
warped mirage
vale wing
#

discord.py is a python library and uses python, logic

warped mirage
#

Once again we are changing the topic but sure

lyric apex
kind trellis
warped mirage
#

I’ll try in the discord.py channel maybe cuz idk no one has answers here

vocal snow
lyric apex
#

👍

#

!d discord.Member.timeout

unkempt canyonBOT
#

await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.10)").

You must have the [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") permission to use this.

This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
warped mirage
vocal snow
#

good

warped mirage
vale wing
#

@warped mirage ok ima be nice and explain try-except to you 😇 (no idea why can't you just read the docs but ok)
So basically try block tries to execute a statement and if it fails, the except block is executed. In your case, the await member.send(...) may fail so you gotta put it to try block and in except put pass or print that bot failed to DM or whatever you want

tough lance
#

hmm... interesting SubaSip

vale wing
#

And behold the spoonfeed

try:
    await member.send(...)
except:
    pass```
#

It's also better to specify the exception

#
except discord.HTTPException:
    ...```
robust fulcrum
visual island
robust fulcrum
#

They are not sending ..........

vocal snow
#

Use a different api

vale wing
#

What does that API even do

robust fulcrum
#

Perrespective best

vocal snow
#

what

robust fulcrum
#

Idk any other api

#

Perrespective api is good

robust fulcrum
vale wing
#

APIs usually have alternatives just tell me what it does

robust fulcrum
#

It returns the toxity in persentage

vale wing
#

Lol nice

visual island
robust fulcrum
#

I cleared the bin last month 😢

vale wing
#

Learn about machine learning and make own toxicity detection AI 🤓

#

Anyway why not just word filter

dusky pine
#

and best part: you don't need to fill any fucking form

shrewd apex
#

perspective works fine i have used it before

#

its pretty accurate

cerulean solstice
#
SSL handshake failed on verifying the certificate
#

oof

warped mirage
#

someone please help me here

#
@client.event
async def on_command_error(ctx, error: Exception):

    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.reply(f'Please specify a user or ID to complete this command', delete_after = 10)
    
    raise error
        

# Mute Command
@client.command(description="Mute the specified user")
@commands.has_permissions(ban_members=True)
async def mute(ctx, member: discord.Member, *, reason=None):
    print("test")
    guild = ctx.guild
    mutedRole = discord.utils.get(guild.roles, name="muted")

    if not mutedRole:
        mutedRole = await guild.create_role(name="muted")

        for channel in guild.channels:
            await channel.set_permissions(mutedRole, speak=False, send_messages=False)
    await member.add_roles(mutedRole, reason=reason)
    await ctx.send(f"{member.mention} has been muted for {reason}")
    try:
        await member.send(f"You have been muted in {guild.name} for {reason}")
    except discord.HTTPException:
        await ctx.reply("This DM could not be sent.")``` mute command doesnt return the error
vale wing
#

What argument do you not specify

warped mirage
#

I need to fix that

vale wing
#

try-except does that

warped mirage
#

Nope

#

I tried still nothing I legit have it in the code****^^^^

#

I tried printing and also doesn’t work

vale wing
#

Does the dm message get sent

warped mirage
#

No it sends on console message coudnt be sent

#

It doesn’t crash bot but I want it as a reply to the user

vale wing
#

What error does it send

warped mirage
vale wing
#

K do please

warped mirage
#

discord.app_commands.errors.CommandInvokeError: Command 'mute' raised an exception: HTTPException: 400 Bad Request (error code: 50007): Cannot send messages to this user

vale wing
#

Could you give the full traceback

warped mirage
#

It says ignoring from mute command

vocal snow
warped mirage
#

Ye I need for a prefix command ,

vale wing
#

Could you just give the full traceback

eager bluff
#

is there a way to get a user by their discord nickname (assuming they are all unique)?

vale wing
#

If they share a guild with bot yes

#

Otherwise I don't think so

eager bluff
warped mirage
vale wing
#

Ok

vale wing
eager bluff
vale wing
#
async def giverole(ctx, member: discord.Member, role: discord.Role)```
#

Roles can only be given to members

eager bluff
#

as in later in the command

vale wing
#

That's a bad way

eager bluff
#

well yeah but i have to use the member/username syntax for other parts and it doesnt work with [username]#4445

vale wing
#
member = await commands.MemberConverter().convert(ctx, "username")```
Iirc it is like this
#

!d discord.ext.commands.MemberConverter

unkempt canyonBOT
#

class discord.ext.commands.MemberConverter(*args, **kwargs)```
Converts to a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member").

All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.

The lookup strategy is as follows (in order)...
vale wing
#

You need to import commands

#

If you need a constant user just use their ID and get object with ctx.guild.get_member(id)

robust fulcrum
visual island
knotty agate
#

how i can get the reactions on a message
for example

channel = client.get_channel(#number)
msg = await channel.send("how many people think im cool")
await msg.add_reaction("\U0001F60E") #sunglasses

@tasks.loop(seconds=1)
async def check_results():
  print(number_of_people_who_reacted)

*ik this program wont work, its just an example

cold oyster
#

I am trying to use on_command_error. When I am asking for a command which is not there, It should send a message, Instead I am getting an error: <disnake.ext.commands.context.Context object at 0x00000183B2DF4EE0>

visual island
cold oyster
# cold oyster I am trying to use on_command_error. When I am asking for a command which is not...
@client.event
async def on_command_error(error, ctx):
    if isinstance(error, commands.CommandNotFound):
        await ctx.reply("**__Command Not Found!__** The command you tried to use was not found. Please do `24?help` for commands list. If this is an error, Please contact `Shaolin_Dragon#9815`.")
    elif isinstance(error, commands.MissingPermissions):
        await ctx.reply("**__Not Allowed!__** You do not have permissions to run that command. Please contact `Shaolin_Dragon#9815` if this is a mistake.")
    else:
        print(error)
knotty agate
cold oyster
#

@visual island Happy bday

visual island
visual island
knotty agate
#

!botvar

unkempt canyonBOT
#

Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:

bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"

@bot.command()
async def get(ctx: commands.Context):
    """A command to get the current value of `test`."""
    # Send what the test attribute is currently set to
    await ctx.send(ctx.bot.test)

@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
    """A command to set a new value of `test`."""
    # Here we change the attribute to what was specified in new_text
    bot.test = new_text

This all applies to cogs as well! You can set attributes to self as you wish.

Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!

cold oyster
#

Lol

visual island
cold oyster
#

I dont get it

visual island
#

ctx should come first, so it should be (ctx, error) not (error, ctx)

cold oyster
#

Right... I am dumb

#

BUT! It was tabnine

visual island
#

anytime 👍

robust fulcrum
#

@visual island

#

I not found it in spam
What should I do now?

#

🥺

visual island
robust fulcrum
#

I mailed them already

visual island
#

no

#

how would you

visual island
robust fulcrum
#

Means i contacted them

robust fulcrum
visual island
robust fulcrum
#

At there contact website

visual island
slate swan
#

googling is sometimes noice

robust fulcrum
#

I not found any good one

slate swan
#

tensorflow would be the best way

robust fulcrum
lavish basin
#

I'm new to building Discord Bots and I have a question on keeping the bots running.

#

Should I run the program on my home computer (very bad probably couldnt handle it with other stuff)

#

Or buy a server to run it on

sick birch
#

The latter

slate swan
#

a suggestion in advance, don't go for something like replit or heroku

slate swan
shell wing
#

So i wanna make a event/cmd that makes the bot send a msg that stays in the end of the channel...like the sticky bot...
how can it be done ?

slate swan
#

Send the message, once a new message has been sent in the channel, send it again?

#

would be annoying as hell lol

#

many bots do that already

proven magnet
#

/level

#

/role

slate swan
#

..

slate swan
#

Invalid syntax at %d

#

Maybe it should be capitalized?

ivory owl
#

can someone give an example of a hybrid command. I am having trouble implementing it

slate swan
wicked atlas
slate swan
#

yeah i was correct 😅

#

Invalided syntax at %d

wicked atlas
#

Can you send the code you use it in?

swift pumice
#

trust

slate swan
wicked atlas
#

Use '' quotes for the string you pass into strftime, otherwise it interrupts the fstring

drifting goblet
#

@glass tangle i need help how 2 multiple file python to discord bot

paper sluice
#

but you are "Not Nakime" pithink

slate swan
#

imposter

cold sonnet
#

impostor*

#

I'm fun at parties

slate swan
#

stop playing so much among us bro

cold sonnet
#

what

#

I'm completely amogusless

slate swan
#

you have among us all over you

slate swan
#

😳

ivory owl
#
class SlashBot(commands.Bot):
    def __init__(self) -> None:
        super().__init__(command_prefix=".", intents=discord.Intents.default())
        
    async def setup_hook(self) -> None:
        self.tree.copy_global_to(guild=discord.Object(id=12345678900987654))
        await self.tree.sync()```
#

in this, should I have a separate setup hook for every server the bot is in?

ivory owl
#

then?

#

what it should be like? do I even need a setup_hook in the first place?

slate swan
#

yes.

#

precisely, a message common could be ideal but a setup hook works fine if you change the guild in copy_global_to

ivory owl
#

how is it even possible if my bot becomes big(not that it will)

slate swan
#

then it'll sync the commands to each server

#

the bot can see

#

and has permissions to create slash commands

ivory owl
#
class SlashBot(commands.Bot):
    def __init__(self) -> None:
        super().__init__(command_prefix=".", intents=discord.Intents.default())
        
    async def setup_hook(self) -> None:
        await self.tree.sync()```
slate swan
#

yes

ivory owl
#

understood

slate swan
ivory owl
#

I have another doubt

slate swan
#

hm?

ivory owl
#

if I wanna have hybrid commands, should it be like

@commands.hybrid_command(with_app_command=True)
@client.tree.command(name="ping", description="Lise test")
async def _ping(interaction: discord.Interaction) -> None:
    await interaction.response.send_message("pong")```
slate swan
#

no

#

you dont need the tree deco then

ivory owl
#
@commands.hybrid_command(with_app_command=True)
async def _ping(interaction: discord.Interaction) -> None:
    await interaction.response.send_message("pong")```
#

then this

slate swan
#

yes.

#

doesnt it take a context though?

#

lemme check rq

#

yes it takes a context

ivory owl
#

Parameters
name (str) – The name to create the command with. By default this uses the function name unchanged.

with_app_command (bool) – Whether to register the command as an application command.

**attrs – Keyword arguments to pass into the construction of the hybrid command.

#

so

@commands.hybrid_command(ctx,with_app_command=True)```
#

wait

slate swan
#

no

ivory owl
#

it should be in the def

slate swan
#

correct

ivory owl
#

then we don't normally need the interaction parameter?

slate swan
#
@commands.hybrid_command()
async def uwu(ctx: commands.Context) -> None:
  ...
#

^

ivory owl
#

got it. let me try if this works

slate swan
slate swan
#

we dont talk about that

ivory owl
#

with that

await interaction.response.send_message("pong")```
becomes
```py
await ctx.send_message("pong")```
slate swan
#

ctx.send

ivory owl
#

ah yes

slate swan
#

Hm

ivory owl
#

great. it doesn't work

slate swan
slate swan
cold sonnet
#

ewu

slate swan
slate swan
ivory owl
slate swan
#

!d
discord.ext.commands.hybrid_command

unkempt canyonBOT
#

@discord.ext.commands.hybrid_command(name=..., *, with_app_command=True, **attrs)```
A decorator that transforms a function into a [`HybridCommand`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.HybridCommand "discord.ext.commands.HybridCommand").

A hybrid command is one that functions both as a regular [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") and one that is also a [`app_commands.Command`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Command "discord.app_commands.Command").

The callback being attached to the command must be representable as an application command callback. Converters are silently converted into a [`Transformer`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Transformer "discord.app_commands.Transformer") with a [`discord.AppCommandOptionType.string`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.AppCommandOptionType.string "discord.AppCommandOptionType.string") type.

Checks and error handlers are dispatched and called as-if they were commands similar to [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command"). This means that they take [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context") as a parameter rather than [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction").

All checks added using the [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") & co. decorators are added into the function. There is no way to supply your own checks through this decorator.

New in version 2.0.
ivory owl
#

wait a min, do I still need client=discord.Client()?

slate swan
#

idk why I missed that

cloud dawn
ivory owl
#

that one is defined

ivory owl
#

but ones using prefix don't

slate swan
ivory owl
#
class SlashBot(commands.Bot):
    def __init__(self) -> None:
        super().__init__(command_prefix=(['li ','Li ']), intents=discord.Intents.default())```
this is what I have
shell wing
#

i need to delete the old msg and resend it once a msg is send in a channel

slate swan
ivory owl
#

now it is just a matter of time to make this work for my older bot

slate swan
glass tangle
#

@drifting gobletI don't konw anything about discord bots…. and, I don't understand what you want: what is "2 multiple file"?

slate swan
#

how to edit a embed field?

sick birch
#

Couldn’t have guessed myself

smoky marsh
#

Any recommended sources except the python discord and the docs?

slate swan
slate swan
#

so
I want a message looking like this: @user, if you fucked up, contact the bot owner which is @me
is it possible to have it indeed ping the user but not ping me in the message?

#

No

#

@slate swan

#

Even this pings me 💀

#

oh dear

slate swan
#

yeah

slate swan
#

.

sturdy tapir
#

how can I thread in discord.py
Preview :
in on ready I've the script check and do requests continuously but I cant use other commands
like
@client.command
because it's a loop, what should I do?

#

C:\Program Files (x86)\Python37-32\lib\threading.py:865: RuntimeWarning: coroutine 'Command.call' was never awaited
self._target(*self._args, **self._kwargs)
this is the error

slate swan
#

command()

sturdy tapir
#

@client.command()
async def add(ctx,id):

vocal snow
#

Nvm

sturdy tapir
sturdy tapir
vocal snow
#

What are you trying to thread

sturdy tapir
#

I threaded for the two

#

the async on_ready function and the async def add

vocal snow
#

Why

sturdy tapir
#

because async on_ready has a while loop

#

and it cant pause or something if I do the add command

slate swan
#

a task would be enough

sturdy tapir
#

can you demonstrate what's a task?

slate swan
#

!d asyncio.create_task

unkempt canyonBOT
#

asyncio.create_task(coro, *, name=None)```
Wrap the *coro* [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine) into a [`Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task "asyncio.Task") and schedule its execution. Return the Task object.

If *name* is not `None`, it is set as the name of the task using [`Task.set_name()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.set_name "asyncio.Task.set_name").

The task is executed in the loop returned by [`get_running_loop()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_running_loop "asyncio.get_running_loop"), [`RuntimeError`](https://docs.python.org/3/library/exceptions.html#RuntimeError "RuntimeError") is raised if there is no running loop in current thread.
slate swan
#

you should use the internal AbstractEventLoop attribute the Bot class has

torn sail
#

Why do u call it AbstractEventLoop

#

Lol

slate swan
#

because Bot.loop returns that class pWut

sturdy tapir
#

hmm

slate swan
#

and its a cool word😳

sturdy tapir
#

that seems hard

torn sail
slate swan
sturdy tapir
#

but okimii

#

the while loop will never end

torn sail
#

Try printing bot.loop

slate swan
#

iirc it returns None or asyncio.AbstractEventLoop afaik

#

None being the place holder pWut

sturdy tapir
#

💀 ok

torn sail
#

Abstract event loop is unimplemented. Just for annotations and stuff

#

It’s never actually used

slate swan
#

it never gets used but it gets set when running the bot afaik

sturdy tapir
#

since I don't understand I'll just make it pause every 3 secs lol

haughty echo
torn sail
#

!e import asyncio; loop = asyncio.new_event_loop(); print(loop)

unkempt canyonBOT
#

@torn sail :white_check_mark: Your eval job has completed with return code 0.

<_UnixSelectorEventLoop running=False closed=False debug=False>
slate swan
#

it returns an internal class? weird

torn sail
#

Abstract event loop is just for typing and stuff

#

And if u wanna make ur own event loop

slate swan
#

are you sure the class that gets shown isnt a child class of AbstractEventLoop or something?

torn sail
#

It is a child class but AbsractEventLoop is something that needs to be subclassed

#

Cause it’s an abc

slate swan
#

i need to check asyncio's src lol

sturdy tapir
#

okimii can I put a async def function in a normal one?

slate swan
slate swan
#

how do I get a desktop friendly clickable message link blobpain

vale wing
sturdy tapir
#

Hmm

#

another question

#

I've a list that a for loop loops around and it's under a while loop

vale wing
#

You mean matrix?

sturdy tapir
#

how do I make the for loop when it finishes the table (finishing doing whatever with all the content of the list) I want it to time.sleep()

vale wing
#

Or what kind of table do you mean

sturdy tapir
#

list

vale wing
#

Ok

sturdy tapir
#

bec if I do a time.sleep after it, it will rest every time she checks one only

vale wing
sturdy tapir
#

will that solve the issue?

vale wing
#

I don't really understand your issue but you definitely shouldn't use time.sleep because it blocks your whole bot

sturdy tapir
#
bounties = ["2887966607","700032621","1858461594"]
@client.event
async def on_ready():
    bounty_channel = client.get_channel(998183276084744232)
    while True:
        for bounty in bounties:
vale wing
#

Ah yes

#

!d discord.ext.tasks.loop use this

unkempt canyonBOT
#

discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
sturdy tapir
vale wing
#

Where did the usage examples go

slate swan
vale wing
#

There surely were some

vale wing
sturdy tapir
vale wing
#

Especially at custom checks

slate swan
#

most decos use nested functions yes

vale wing
#

@sturdy tapir scroll up the examples are on top of that docs page, there are examples for cogs and non cogs

sturdy tapir
#

found this

#

@tasks.loop(seconds = 10) # repeat after every 10 seconds
async def myLoop():
# work

vale wing
#

You need to start it too

#

Also naming convention 🤯

sturdy tapir
#

@client_event

vale wing
#

It is a separate func

sturdy tapir
#

sorry

sturdy tapir
vale wing
#

3rd code block from very top

#

You don't even need most of that stuff

sturdy tapir
#

What do I need exactly?

vale wing
#
@tasks.loop(minutes=5)
async def my_task():
    # await bot.wait_until_ready()
    ...

my_task.start()```
sturdy tapir
#

oooo

#

that will do it

vale wing
#

You might need to wait until ready might not, depends on your case

sturdy tapir
#

I'll test it

slate swan
#

it depends on the variant

sturdy tapir
#

weird

#

it didn't wait

slate swan
#

python can/does use camel case either way

coral geyser
#

How would I index the bot itself to change like the nickname of it?

#

I kinda forgot

slate swan
#

!d discord.ClientUser.edit