#discord-bots

1 messages · Page 806 of 1

slate swan
#

andy said he was gonna publish when he has all the base model objs

maiden fable
slate swan
maiden fable
#

Lmao

slate swan
#

How much would you rate the difference between discord.py and disnake?? (10 means a lot of difference in code, while 1 being the lowest)

#

1

#

ouch nice

#

wasnt hard at all

#

\👍 thanks

#

just change name thats all

#

and for the timeout endpoint its just like any other

#

!d disnake.Member.timeout

unkempt canyonBOT
#

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

Times out the member from the guild; until then, the member will not be able to interact with the guild.

Exactly one of `duration` or `until` must be provided. To remove a timeout, set one of the parameters to `None`.

You must have the [`Permissions.moderate_members`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.moderate_members "disnake.Permissions.moderate_members") permission to do this.

New in version 2.3.
slate swan
#

lol

#

thanks :) I will look in the documentation :)

#

yw

#

i am using pytube to search the youtube videos(for the music bot), how do i get only the videoid from the pytube search feature
(wrong channel?, should i post it on general?)

pliant gulch
#

It's been on pypi since 0.1.1

#

ALso select menus are added!

shadow wraith
#

if so please don't

#

!ytdl

unkempt canyonBOT
#

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
gilded gust
#

So im developing a discord bot and I'm using threading, the problem is my thread target is an async function, so i dont know how to properly pass it in as the target for my thread, can anyone help?
Here's a small code sample: ```py
async def func1(self):
...
for interval in intervals:
thread = Thread(target=self.spawn, args=(channel, interval))
threads.append(thread)
async def spawn(self, channel, interval):
...

Error:py
RuntimeWarning: coroutine 'Spawning.spawn' was never awaited
self._target(*self._args, **self._kwargs)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

I know its not really an *error*, but my task still didnt start.
pallid mango
#

does anyone have a fivem server member count code?

slate swan
#

🥴 not going to ad that bot everywhere

slate swan
#

As the error says

gilded gust
#

uhm how so

unkempt canyonBOT
#

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
slate swan
#

await function ()

gilded gust
slate swan
#

you still need to await it if it's a coroutine

#

Just started disnakepy @client.slash_command(guild_ids=[927159708169674762]) async def ping(ctx): await ctx.send('Pong!')Made this but will it take some time to register?

gilded gust
#
thread = await Thread(target=self.spawn, args=(channel, interval))
```Like this?
slate swan
#

target = await self.spawn

gilded gust
#

i tried that

#

it gave an error

#

imma show it to u 1 sec

slate swan
slate swan
#

great

gilded gust
#

@slate swan ```py
Traceback (most recent call last):
await ctx.command.invoke(ctx)
await injected(*ctx.args, **ctx.kwargs)
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: object method can't be used in 'await' expression

slate swan
gilded gust
#
    thread = threading.Thread(target=await self.spawn, args=(channel, interval))
TypeError: object method can't be used in 'await' expression
#

oh

#

ok 1 sec

#

so do i have to pass in the args normally now?

slate swan
#

Why don't you just call the function normally, instead of using a thread?

gilded gust
#

because i need to have this running in multiple different channels at the same time

gilded gust
#

no i'll try

slate swan
gilded gust
slate swan
#

use an async function instead of thread

slate swan
slate swan
gilded gust
shadow wraith
slate swan
slate swan
proper root
#

Been looking at the tanjun examples, I was wondering what .set_type_dependency does

tanjun.Client.from_gateway_bot(bot)
        .load_modules("examples.complex_component")
        # Both slash commands and message commands can be automatically executed
        # by a gateway bot bound client
        .load_modules("examples.message_component")
        .load_modules("examples.slash_component")
        .add_prefix(loaded_config.prefix)
        .set_prefix_getter(get_prefix)
        .set_type_dependency(config.ExampleConfig, loaded_config)
        .set_type_dependency(protos.DatabaseProto, database)
        # Here we use client callbacks to manage the database, STOPPING can also be used to stop it.
        .add_client_callback(tanjun.ClientCallbackNames.STARTING, database.connect)
slate swan
shadow wraith
#

nope

gilded gust
slate swan
slate swan
shadow wraith
#

chids

slate swan
#

channelids

slate swan
#

I used lightbulb as my command handler

gilded gust
#

so like it sends a message in channel 1, then waits 8 seconds, and while its waiting it sends a message in channel 2 and waits 12 seconds, after the 8 seconds are up it send a different message in channel 1, and so on

#

@slate swan do you know how to do so?

slate swan
gilded gust
#

whats the difference between time.sleep and asyncio.sleep

slate swan
#

time.sleep will make the whole bot sleep and the bot will not respond to other commands also
while asyncio does not make the whole bot sleep and the bot will be able to respond to other commands

gilded gust
#

oh ok

slate swan
#

\👍

gilded gust
#

imma just test it out real quick brb

slate swan
#

\👍

strong vessel
#

do the slash commands actually mean anything or is it just discord trying to pretend it means something

strong vessel
#

would users actually like using it?

#

compared to the normal prefix

slate swan
#

Hmm people don't really use much slash commands

strong vessel
#

yeah

#

nvm i'm trying to avoid doing stuff that is not 'normal' to users, since users seem to struggle with things that are 'not normal'

slate swan
#

lel \👍

#

😭

strong vessel
#

response: awoo

gilded gust
# slate swan \👍

theres some small bugs, but i think i can fix them, tysm for all your help

slate swan
#

\👍 :)

gilded gust
#

wait new problem

#

nvm im just dumb

#

so basically whats happening is it runs the spawn command but then runs the wait, and it only goes to the next iteration when the wait is complete, which is not what i want @slate swan can you help?

strong vessel
#

if there is wait of course it would wait?

#

that's what the wait does?

gilded gust
#

yes i know

#

so i need to change it to something else

strong vessel
#

just return maybe

gilded gust
#

but idk to what

#

why?

strong vessel
#

oh nvm

#

yeah its structure wouldn't work as is, you want an iteration that executes a bunch of stuff. all i can think of is to put the await outside of the iteration. i'm no expert though but it's my best guess

#

actually idk

gilded gust
#
1111111      11111111
       22222222      2222222
               33333333          3333333
       |-----||------|-----------|
          6s     8s       12s
``` This is kinda how i want it to be where a ton of ones means task 1, a ton of two means task 2, etc (not for scale)
strong vessel
#

i don't get it

#

oh i see

gilded gust
#

yea

#

I'll show you whats happening now 1 sec

strong vessel
#

you wanted to preserve the chronology 1->2->3 but able to execute these jobs in parallel

#
for i in jobs
  await 1
  await 2
  await 3
#

oops no

gilded gust
#
111111                                        111111
              2222222
                             333333       
      |-----|        |------|      |----------|
        6s              8s              12s
``` This is how its going on rn
strong vessel
#

idk but maybe need to use a generator

#

this is way beyond me tbh i can't figure it out

gilded gust
#

thats why i thought i should use threading

slate swan
#

ye you should use threading then

#

so have you tried useing threading

gilded gust
#

i did try

slate swan
#

so whats the result?

gilded gust
#

error

slate swan
#

what erro

strong vessel
#

sounds painful though, because if you wanted to run threads in parallel in python it becomes really error-prone due to GIL

slate swan
gilded gust
#

ooh i found a solution on stack overflow

slate swan
#

Try doing this```py
async def func1(channel, interval): #the function we wanted to run
#do something

def triggeer_func1(channel, interval): #an alternative function to trigger the function we want to run
asyncio.run(func1(channel, interval))

thread=threading.Thread(target=trigger_func1, args=(channel, interval)) #run the alternative function
thread.start()```

gilded gust
#

ok imma test it out

gusty hatch
#

how would I make a dropdown for an embed with nextcord

slate swan
#

You can also do```py
async def func1(channel, interval): #the function we wanted to run
#do something

thread=threading.Thread(target=asyncio.run, args=(func1(channel, interval))) #run the main function
thread.start()```

slate swan
gusty hatch
#

.snipe

pallid mango
#
@client.command()
@commands.has_permissions(kick_members=True)
async def globalban(ctx, user : discord.User, reason=None):
  if user == None:
    await ctx.reply("Please mention a user!")
  else:
    for guild in client.guilds:
      await ctx.discord.User.send("You have been permanently global banned from SALRP!")
      await guild.ban(user, reason=reason)```
slate swan
pallid mango
#

im imaging the ctx.discord.User.send is not right AT ALL dont worry

#

i just want to send a message to the user we are banning

slate swan
#

do thispy await user.send('your message')

slate swan
velvet tinsel
#

What’s he trying to do?

slate swan
pallid mango
gilded gust
#

its really long i'll send you the end

RuntimeError: Task <Task pending name='Task-20' coro=<Spawning.spawn() running at  cb=[_run_until_complete_cb() at  got Future <Future pending cb=[shield.<locals>._outer_done_callback() at  attached to a different loop
Future exception was never retrieved
future: <Future finished exception=ServerDisconnectedError('Server disconnected')>
aiohttp.client_exceptions.ServerDisconnectedError: Server disconnected
pallid mango
#

thank you

maiden fable
#

👀

slate swan
maiden fable
#

Not targeting u or smth

slate swan
maiden fable
#

Just a general question

maiden fable
slate swan
strong vessel
#

unicode keeps dumping massive numbers and symbols it is so annoying

slate swan
#

:>

strong vessel
#

idk how to deal with it

strong vessel
#

like ok 230948q3059283532052345345

#

jfl what i'm gonna do with the 20358239537235235 unicode

slate swan
slate swan
#

is it true or just a rumor?

maiden fable
#
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠿⠿⠿⠿⠿⠿⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⣉⡥⠶⢶⣿⣿⣿⣿⣷⣆⠉⠛⠿⣿⣿⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⡿⢡⡞⠁⠀⠀⠤⠈⠿⠿⠿⠿⣿⠀⢻⣦⡈⠻⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⡇⠘⡁⠀⢀⣀⣀⣀⣈⣁⣐⡒⠢⢤⡈⠛⢿⡄⠻⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⡇⠀⢀⣼⣿⣿⣿⣿⣿⣿⣿⣿⣶⣄⠉⠐⠄⡈⢀⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⠇⢠⣿⣿⣿⣿⡿⢿⣿⣿⣿⠁⢈⣿⡄⠀⢀⣀⠸⣿⣿⣿⣿
⣿⣿⣿⣿⡿⠟⣡⣶⣶⣬⣭⣥⣴⠀⣾⣿⣿⣿⣶⣾⣿⣧⠀⣼⣿⣷⣌⡻⢿⣿
⣿⣿⠟⣋⣴⣾⣿⣿⣿⣿⣿⣿⣿⡇⢿⣿⣿⣿⣿⣿⣿⡿⢸⣿⣿⣿⣿⣷⠄⢻
⡏⠰⢾⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠟⢂⣭⣿⣿⣿⣿⣿⠇⠘⠛⠛⢉⣉⣠⣴⣾
⣿⣷⣦⣬⣍⣉⣉⣛⣛⣉⠉⣤⣶⣾⣿⣿⣿⣿⣿⣿⡿⢰⣿⣿⣿⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣧⡘⣿⣿⣿⣿⣿⣿⣿⣿⡇⣼⣿⣿⣿⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣇⢸⣿⣿⣿⣿⣿⣿⣿⠁⣿⣿⣿⣿⣿⣿⣿⣿⣿
strong vessel
#

omg that looks like fun

gilded gust
#

nice

strong vessel
#

i'd never use it for anything though idk

maiden fable
#

Doesn't work on mobiles tho

slate swan
#

ah so bad

slate swan
strong vessel
#

i'm sure it will work on mobile eventually

maiden fable
strong vessel
#

discord seems to put massive effort into stuff like this

maiden fable
#

Mhm

slate swan
maiden fable
#

BTW fun fact: Mobiles still don't have support for user and message commands

strong vessel
#

oof

maiden fable
#

The commands u get after right clicking a user/message and going to apps option

slate swan
#

ah

#

ye

#

lel

quick gust
strong vessel
#

why is it so hard to dm a bot

quick gust
#

it's not

strong vessel
#

like the process is i have to make a private server, add the bot to the server, then dm the bot.
if i try to copy paste the 'bot dm link' it will not work

#

i wish i could just copy paste a 'bot dm link'. even if i try to 'look up the bot name in dm' it doesn't seem to work

quick gust
#

huh?

#

if you have the bot ID u can just go to https://discord.com/users/id

spring flax
#

Is the ainsi support fully released?

quick gust
#

not for mobiles

strong vessel
#

in order for the copy paste dm link to work, you need to have dmed the bot, but then, the bot cannot dm you unless it has a mutual server with you, which effectively means you'd need to have added the bot to your private server

median flint
#

SOMEONE HELP ME MY BRAIN IS DYING

#
@client.command()
async def job(ctx):
  user = ctx.author
  em = discord.Embed(title= "Jobs", color=discord.Color.random())
  for i in jobs:
    print(i)
    print(jobs[i])
    print(jobs[i["pay"]])
    em.add_field(name = i, value="Pay: {} | XP:  {}".format(jobs[i["pay"]], jobs[i["XP"]]))
  await ctx.send(embed = em)```
strong vessel
median flint
#

WHY WONT THIS WORK

median flint
#

There is no error

#

it just wont work

quick gust
slate swan
#

jobs defined?

median flint
#
jobs = {
  "Janitor": {"pay": 1500, "XP": 50, "XPneeded": 0},
  "Teacher": {"pay": 0, "XP": 250, "XPneeded": 500}
}
strong vessel
quick gust
slate swan
#

try printing something after each line and see where it stops

median flint
strong vessel
quick gust
strong vessel
quick gust
#

are u in a mutual server with the bot?

slate swan
strong vessel
quick gust
quick gust
#

oh then what he sent later was different ig

slate swan
#

ye

quick gust
median flint
#

nope

#

it says nothing it just doesn't run

slate swan
#

have you tried printing after em.add_field()???

median flint
#

and if I try writing a print(jobs[i["pay"]]

median flint
slate swan
#

hmmm....

median flint
#
@client.command()
async def job(ctx):
  user = ctx.author
  em = discord.Embed(title= "Jobs", color=discord.Color.random())
  for i in jobs:
    print(jobs[i["pay"]])
    em.add_field(name = i, value="Pay: {} | XP:  {}".format(jobs[i["pay"]], jobs[i["XP"]]))
  await ctx.send(embed = em)
#

didn't print anything after I ran it in my server

slate swan
#

try thispy try: em.add_field() #fill it except Exception as e: print(e) print(em)

median flint
#

Nothing printed

#

I don't think the problem is the em.addfield

#

I think it's the jobs[i["pay"]]

slate swan
#

ah

#

Lol

#

I figured out

median flint
#

what is it

slate swan
#

replace jobs[i["pay"]] with jobs[i]["pay"] lol it was a common error

median flint
#

GOD

#

NOWHY

slate swan
#

lol

median flint
#

HOW DID I LET THIS HAPPEN

#

I'VE BEEN USING PYTHON FOR A YEAR

strong vessel
#

pwned jfl

median flint
#

NOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO

slate swan
#

Haha

strong vessel
#

shrekt

slate swan
#

and the thing is that no one noticed lol

median flint
#

lol

strong vessel
#

i guess the [i["pay"]], jobs[i["XP"] part too

slate swan
#

ye

#

every list part

strong vessel
#

idk though i mean if i was a job object containing pay and XP it would make sense

#

oops nvm

#

it would then be i["pay"] instead of jobs[i["pay"]] but still not jobs[i]["pay"]

slate swan
#

can i use async twice under @client.command()?

cursive hollow
#

How to make a bot online ;-;

quick gust
#

what do u mean? you only define a function once

cursive hollow
#

My bots not coming online

quick gust
quick gust
slate swan
cursive hollow
#

Yes

strong vessel
#
@client.command()
async def job(ctx):
  user = ctx.author
  em = discord.Embed(title= "Jobs", color=discord.Color.random())
  for job in jobs:
    print(job["pay"])
    em.add_field(name = job, value="Pay: {} | XP:  {}".format(job["pay"], job["XP"]))
  await ctx.send(embed = em)
cursive hollow
#

Error

quick gust
#

show error

slate swan
#

do you want print statement to be in just terminal?

cursive hollow
#

Wait

quick gust
slate swan
#

hmm

strong vessel
#

idk just guessing

quick gust
#

dont spoonfeed btw, they understood whats wrong so they'll do it on their own

slate swan
#

im too noob to spoonfeed lmao

#

im like day 4 into coding

#

you should not name a variable inside a function same as the function name :')

#

^

#

where is jobs defined btw @strong vessel

strong vessel
slate swan
#

well if its not defined then you can't get anything lol

strong vessel
#

i was replying to someone else question

slate swan
#

i presume that jobs is either a dictionary or a list

#

mhm, and seems like they solved the issue already

strong vessel
#

idk i have no idea i was just guessing

slate swan
strong vessel
#

yeah its all good

slate swan
strong vessel
#

so discord bots can mass spam by DMing every person in every server it is in?

#

i mean i know the welcome bots do that

#

i'm not trying to spam of course, but trying to see if i can DM everyone

quick gust
#

of course, and its against the ToS if you do it with the purpose to spam them

slate swan
#

Yes, sure

pallid mango
#
@client.event()
async def on_message_delete(message):
    embed=discord.Embed(title="{} deleted a message".format(message.member.name), description="", color="Blue")
    embed.add_field(name= message.content, value=f"This message has been deleted by {message.user}!")
    channel=client.get_channel(919024469023002631)
    await channel.send(channel, embed=embed)```
#

getting something about coro

strong vessel
#

is it spam if i'm trying to provide a welcome message to the bot? like just one message

slate swan
#

no need of brackets

pallid mango
#

oh

strong vessel
#

ok i can try to implement that ig

quick gust
#

since the purpose is a welcome message, not to spam someone

slate swan
strong vessel
quick gust
#

Oh

quick gust
#

still should be good I think?

#

yeah it should be

#

tons of bots do it

strong vessel
#

also i don't understand why when i copy paste the bot link to add to server it is permissions=0 but ig still able to read and send messages which is more than permissions 0?

quick gust
#

you're talking about dming a user when they first use your bot right?

pallid mango
#
@client.event
async def on_message_delete(message):
    embed=discord.Embed(title="{} deleted a message".format(message.user.name), description="", color="Blue")
    embed.add_field(name= message.content, value=f"This message has been deleted by {message.user}!")
    channel=client.get_channel(919024469023002631)
    await channel.send(channel, embed=embed)```
#

now its saying message has no attribute user

strong vessel
quick gust
#

Ok yeah thats spammy

strong vessel
#

yeah i'll just do the first use thing

slate swan
pallid mango
#

ngl i might be to tired and hungover to be coding lmfao

quick gust
#

do the first use thing, yes

slate swan
median flint
pallid mango
#

okay

slate swan
unkempt canyonBOT
pallid mango
#

File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event await coro(*args, **kwargs) File "main.py", line 70, in on_message_delete embed=discord.Embed(title="{} deleted a message".format(message.author), description="", color="Blue") File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/embeds.py", line 115, in __init__ self.colour = colour File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/embeds.py", line 230, in colour raise TypeError('Expected discord.Colour, int, or Embed.Empty but received %s instead.' % value.__class__.__name__) TypeError: Expected discord.Colour, int, or Embed.Empty but received str instead.

#

oh color is wrong isnt it

slate swan
#

color should be an object, or an integer

#

use discord.Color.blue() there

clever field
#

i have ini file with section "analogue"

[analogue]
poll: ["голосовать","poll","suggest","голос"]

if copy in

@commands.command(aliases=config['analogue']['poll'])

console writing this
nextcord.ext.commands.errors.ExtensionFailed: Extension 'modules.system' raised an error: TypeError: Aliases of a command must be a list or a tuple of strings.
how fix this ?

maiden fable
slate swan
maiden fable
maiden fable
maiden fable
slate swan
clever field
maiden fable
maiden fable
maiden fable
clever field
#

thx

pallid mango
#
  @commands.has_role("SALRP | High Staff Team","SALRP | Asst. Lead Developer","SALRP | Media Director","SALRP | Gang Management","SALRP | Business Management","SALRP | Manager Assistant","Discord Appeals Team","SALRP | Head of Support Team","Department High Command"=True)```
maiden fable
#

Huh?

pallid mango
#

okay so basically, i want the command to work if a user has any of these roles

quick gust
#

has_any_role right?

maiden fable
#

!d discord.ext.commands.has_any_role

unkempt canyonBOT
#

@discord.ext.commands.has_any_role(*items)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has **any** of the roles specified. This means that if they have one out of the three roles specified, then this check will return True.

Similar to [`has_role()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.has_role "discord.ext.commands.has_role"), the names or IDs passed in must be exact.

This check raises one of two special exceptions, [`MissingAnyRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") if the user is missing all roles, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").

Changed in version 1.1: Raise [`MissingAnyRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
pallid mango
#

so just change to commands.has_any_role

quick gust
#

yeah

pallid mango
#

wait it says something when i hover over one of them

quick gust
#

but it will check for only one role, so if the author has even one of the roles, it will execute the command

maiden fable
#

Remove the =True

pallid mango
#

ohhh

#

thank you hunter

slate swan
#

has_role is also a thing but it checks if the author has. All the role mentioned

clever field
#
    @commands.command(aliases=[config['analogue']['poll']])
    async def __POLL(self, ctx, *, arg):

new problem, bot can't find alias. on_command_error is triggered
only __POLL working

pallid mango
#

Ignoring exception in on_message_delete Traceback (most recent call last): File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event await coro(*args, **kwargs) File "main.py", line 73, in on_message_delete await channel.send(embed=embed) File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/abc.py", line 1065, in send data = await state.http.send_message(channel.id, content, tts=tts, embed=embed, File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/http.py", line 254, in request raise HTTPException(r, data) discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body In embed.fields.0.name: This field is required

#

why does my console send this every now and then

quick gust
#

why the config, and it takes a list

clever field
quick gust
#

!d discord.ext.commands.Command.aliases

unkempt canyonBOT
clever field
#

if it is not added back to the list, an error will appear that it is not a list or a tuple

#

Union[List[str], Tuple[str]] means nothing to me

pallid mango
#
  @commands.command()
  @commands.guild_only()
  async def temprole(ctx, member:discord.Member=None, time2=None):
    guild = ctx.guild
    role = discord.utils.get(guild.roles, name="Role")
    time_convert = {"s":1, "m":60, "h":3600,"d":86400}
    if member == None:
      return await ctx.send("You have to mention the member that you want to add the role to!")
    if time2 == None:
        return await ctx.send("You have to type the time for which you want to give the role to the mentioned member!")
    with open("data.json") as f:
      data = json.load(f)
    if str(member.id) in data:
        return await ctx.send("hmm")
    with open("data.json") as f:
      data = json.load(f)
      data[member.id] = {"time": time2, "role": role.mention}
    with open("data.json", "w") as f:
        json.dump(data, f)
    with open("data.json", "r") as f:
      data = json.load(f)
      time3 = data[str(member.id)]["time"]
    temprole = int(time3[:-1]) * time_convert[time3[-1]]
    await member.add_roles(role)
    await ctx.send(f"Successfully added the `{role.name}` role to **{member.name}#{member.discriminator}** for {time3}")
    await asyncio.sleep(temprole)
    await member.remove_roles(role)
    with open("data.json") as f:
      data = json.load(f)
      data.pop(str(member.id))
    with open("data.json", "w") as f:
        json.dump(data, f) 
    await ctx.send("done")```
#

this is in a mods folder

#

Traceback (most recent call last): File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke await ctx.command.invoke(ctx) File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke await injected(*ctx.args, **ctx.kwargs) File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Mods' object has no attribute 'guild'

visual island
#

on classes

pallid mango
#

i will try

#

i forget cog stuff needs to have self in it

#

Traceback (most recent call last): File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke await ctx.command.invoke(ctx) File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke await injected(*ctx.args, **ctx.kwargs) File "/home/runner/SALRP/venv/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: FileNotFoundError: [Errno 2] No such file or directory: 'data.json'

pallid mango
#

no clue lol

quick gust
#

is it in the same folder as your cogs file?

quick gust
clever field
#

create this file and repeat this

pallid mango
#

okay

quick gust
#

you need a data.json file to open it!

pallid mango
clever field
#

data.json create in bot folder

pallid mango
#

put it in my cogs folder?

clever field
#

nope

pallid mango
#

im using replit

clever field
#

u can write directory file in code

#

or copy in folder bot

clever field
pallid mango
#

is this right?

clever field
#

yep

pallid mango
#

is that all i need lmfao

clever field
#

maybe

pallid mango
#

`Ignoring exception in command temprole:
Traceback (most recent call last):
File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/runner/SALRP/cogs/Mods.py", line 70, in temprole
data = json.load(f)
File "/nix/store/wlhmpa2qk786ddp05ahv3jjlds6d44a5-python3-3.8.12/lib/python3.8/json/init.py", line 293, in load
return loads(fp.read(),
File "/nix/store/wlhmpa2qk786ddp05ahv3jjlds6d44a5-python3-3.8.12/lib/python3.8/json/init.py", line 357, in loads
return _default_decoder.decode(s)
File "/nix/store/wlhmpa2qk786ddp05ahv3jjlds6d44a5-python3-3.8.12/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/nix/store/wlhmpa2qk786ddp05ahv3jjlds6d44a5-python3-3.8.12/lib/python3.8/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)

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/runner/SALRP/venv/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: JSONDecodeError: Expecting value: line 1 column 1 (char 0)`

clever field
#

create in data.json this

{

}
pallid mango
clever field
#

yep

quick gust
#

youll also need to have data in there though...?

pallid mango
#

Traceback (most recent call last): File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke await ctx.command.invoke(ctx) File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke await injected(*ctx.args, **ctx.kwargs) File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'mention'

clever field
pallid mango
#
      data[member.id] = {"time": time2, "role": role.mention}```
#

here

#

is where it drops error

clever field
#

wait

#

throw off the code

pallid mango
#
  @commands.command()
  @commands.guild_only()
  async def temprole(self, ctx, member:discord.Member=None, time2=None):
    guild = ctx.guild
    role = discord.utils.get(guild.roles, name="Role")
    time_convert = {"s":1, "m":60, "h":3600,"d":86400}
    if member == None:
      return await ctx.send("You have to mention the member that you want to add the role to!")
    if time2 == None:
        return await ctx.send("You have to type the time for which you want to give the role to the mentioned member!")
    with open("data.json") as f:
      data = json.load(f)
    if str(member.id) in data:
        return await ctx.send("hmm")
    with open("data.json") as f:
      data = json.load(f)
      data[member.id] = {"time": time2, "role": role.mention}
    with open("data.json", "w") as f:
        json.dump(data, f)
    with open("data.json", "r") as f:
      data = json.load(f)
      time3 = data[str(member.id)]["time"]
    temprole = int(time3[:-1]) * time_convert[time3[-1]]
    await member.add_roles(role)
    await ctx.send(f"Successfully added the `{role.name}` role to **{member.name}#{member.discriminator}** for {time3}")
    await asyncio.sleep(temprole)
    await member.remove_roles(role)
    with open("data.json") as f:
      data = json.load(f)
      data.pop(str(member.id))
    with open("data.json", "w") as f:
        json.dump(data, f) 
    await ctx.send("done")```
clever field
#

copy in data.json

{
"time":{},
"r":{}
}
pallid mango
#

okay, done

clever field
#

I do everything through a translator, I can not understand everything

pallid mango
clever field
#

It's my pleasure

pallid mango
#

Traceback (most recent call last): File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke await ctx.command.invoke(ctx) File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke await injected(*ctx.args, **ctx.kwargs) File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'role'

#

I changed role.mention to ctx.role.mention, and I got passed that part of code and now I have this error.

pallid mango
clever field
#

wait

stuck flare
clever field
#

u have already ROLE

#

if u need mention author

stuck flare
clever field
stuck flare
#

mk

pallid mango
clever field
#

better using nextcord

clever field
#

if u need mention ROLE

#

role.mention

stuck flare
pine crown
#

How to delete files with python

pallid mango
#

`Ignoring exception in command temprole:
Traceback (most recent call last):
File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/runner/SALRP/cogs/Mods.py", line 75, in temprole
data[member.id] = {"time": time2, "role": role.mention}
AttributeError: 'NoneType' object has no attribute 'mention'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'mention'`

#

this is the error i get

clever field
stuck flare
stuck flare
clever field
#

almost nothing has changed there, except for the names of some classes

pallid mango
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'mention'

#

why does it show this error?

quick gust
#

your role is none

clever field
#

where role ?

pallid mango
#
    role = discord.utils.get(guild.roles, name="Role")```
clever field
#

on server have role ?

pallid mango
#

im not understanding

clever field
#

on the server where there is a bot, is there this role?

pallid mango
#

no

clever field
#

create role

pallid mango
#

all i have to do is name it "Role"?

clever field
#

name="Role" or rename this

#

yep

pallid mango
#

okay

#

so can i use a pre-existing role then?

pine crown
#

f

clever field
#

yes

pine crown
#

Yes

pallid mango
#

okay, it sent hmm

#

"hmm"

#
    if str(member.id) in data:
        return await ctx.send("hmm")```
pine crown
sullen surge
#

Sorry to interrupt, but If I'm doing a loop, it's ok if I open client every time in the loop, as long as I close it, right? I have a discord bot that is working only on the first instance of an event happening, but then will not work after the second or third or later instances.

clever field
#

guild = ctx.guild
await guild.create_role(name="role name")

pine crown
#

await guild.create_role(name="Role")

pallid mango
#

no i dont need to create

#

i set it to random role only owner has

pine crown
#

?

pallid mango
#

this is a temprole command, does it matter what role i set it to?

clever field
#

the translator tells me some kind of nonsense, but I will try to explain

clever field
#

it's more like a crutch, if u need optimization for bot

fluid spindle
#

Is it possible to change the time-out duration of a View?

sullen surge
#

I have a loop that finds places in the US where the weather meets a condition. Then within that loop, if it's in a certain state, I set a variable to 1. If that variable is 1 (within the bigger loop), then I execute this code:

if discordnumber == 1:
                        client = discord.Client()

                        @client.event
                        
                        async def on_ready():
                            print('We have logged in as {0.user}'.format(client))
                            channel = client.get_channel(channelid)
                            await client.wait_until_ready()
                            await channel.send(discordtext)
                            await client.close()
                            
                        client.run('token')
#

But this only works on the first instance, not on later ones. This bot also sends a tweet, which works, so it's not a script error elsewhere.

clever field
#

I don't even know how to do it

#

there it can work for a couple more seconds

#

after closing

stuck flare
#

@clever field with the tutorial u shared is there any video for it

clever field
#

wait

#

i have russian guides

stuck flare
#

eng?

clever field
#

all english guides bullshit

#

i finding

stuck flare
#

oh

#

give russian i guess

clever field
#

maybe glowstick can help u

sullen surge
clever field
#

idk

sullen surge
#

Darn, ok.

#

Well, let me ask a different way. What's the best way to set up a bot to send a message whenever something happens in the backend. Should I open the connection then use an event other than on_ready() to send it?

pallid mango
#

OSError: [Errno 98] Address already in use

#

how do i fix this in my keep_alive.py

clever field
#

aaaakh

clever field
#

channel = bot.get_channel(ID)

#

await channel.send(MESSAGE)

sullen surge
#

And that doesn't have to be within an async function?

clever field
#

maybe I misunderstood the message

clever field
#

I'm probably going to do more than my bot

sullen surge
#

MySQL database being updated, I'm hitting it with Python and when I get a valid result, I want to tweet it (this works always) and send a message to a discord server (this works, but only the first instance). So I tend to think it's something with my discord portion of the script

vale wing
#

You update the database with the external python script right?

sullen surge
#

Yeah exactly, all that stuff works perfectly

#

And the tweeting script works perfectly, a few days ago someone asked for the discord functionality

vale wing
#

You want to make the bot do something from the script that interacts with the db, am I correct?

valid galleon
#

so im trying to get the id of the mentioned channel in the command, and im type hinting the param "channel" to discord.TextChannel. when i use channel.id, i get the error:
Converting to "_UnionGenericAlias" failed for parameter "channel".

vale wing
sullen surge
#

Yeah it's basically something like this:

  1. Event happens in real world
  2. External python script updates mysql database
  3. Script in question searches mysql database and has a new result
  4. If item hasn't previously been tweeted/sent to discord, then tweet it and send to discord via this code here: #discord-bots message
vale wing
#

Personally I just send raw requests to discord API in such case, but there must be a better method

#

Usually the apps are integrated into bots

#

There are several ways to implement this ig

sullen surge
#

Here's a bigger example of code if it helps

#
    try:
        with connection.cursor() as cursor:
            sql = "query in here" 
            try:
                cursor.execute(sql,currentdate)
            except Exception as e:
                print(e)
            cur = cursor.fetchall()
    except:
        print('sql fail')
    try:
        if len(cur) > 0:
            for item in cur:
                discordnumber = 0
                if item['weather'] == 'Sun':
                    hash = '#Sun '
                elif item['weather'] == 'Rain':
                    hash = '#NCAAM #CBB '
                    discordnumber = 1
                else:
                    hash = '#' + item['weather'] + ' '           

#
                if item['station_id'] in masterlist: 
                    if str(item['overtime']) == str(masterlist[item['station_id']]['overtime']):
                        #print('Yeah we already saw')
                        pass
                    else:
                        if item['temperature'] > item['dew_point']:
                            discordtext = (weatheralerttext)
                        else:
                            discordtext = (weatheralerttext2)                           
                        api.update_status(tweet)
                        if discordnumber == 1:
                            print('discord is 1, it got this far at least')
                            client = discord.Client()
                            print('it even recognized discort.client()')
                            @client.event
                            async def on_ready():
                                print('We have logged in as {0.user}'.format(client))
                                channel = client.get_channel(channelid)
                                await client.wait_until_ready()
                                await channel.send(discordtext)
                                await client.close()                        
                            client.run('token')
                else:
                    if item['temperature'] > item['dew_point']:
                        discordtext = (weatheralerttext)
                    else:
                        discordtext = (weatheralerttext2)   
                    api.update_status(tweet)

#
                    masterstationlist[item['station_id']] = {'overtime':item['overtime']}
                    if discordnumber == 1:
                        client = discord.Client()
                        @client.event
                        async def on_ready():
                            print('We have logged in as {0.user}'.format(client))
                            channel = client.get_channel(channelid)
                            await client.wait_until_ready()
                            await channel.send(discordtext)
                            await client.close()
                        client.run('token')
vale wing
stuck flare
#

i dont understand whats "ctx" can someone explain it to me

sullen surge
#

raw request seems to be the way, do you happen to know of any good tutorials? My bot is so simple I don't want to overthink this

vale wing
vale wing
#

!pypi requests

unkempt canyonBOT
vale wing
unkempt canyonBOT
#
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.

This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.

This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable "discord.abc.Messageable") ABC.
valid galleon
# vale wing Could you show code and how you use the command?

i use it to to add/edit stuff inside a mongodb collection:

    @commands.command()
    @commands.has_permissions(administrator = True)
    async def setmodlog(self, ctx, channel = Optional[discord.TextChannel]):
        if channel is None:
            await ctx.send('Please Specify the channel')
        else:
            chan_id = channel.id
            print(chan_id)
            res = log_chancoll.find_one({'guild_id': ctx.guild.id,
                                   'channel_id': chan_id})
            if res is None:
                log_chancoll.insert_one({'guild_id': ctx.message.guild.id,
                                         'channel_id': chan_id,
                                         'toggle': True})
                await ctx.send('ModLog has been turned on')
            elif res is not None:
                res = res.get('toggle')
                if res == True:
                    await ctx.send('Modlog is already turned on')
                elif res == False:
                    log_chancoll.update_one({'guild_id': ctx.message.guild.id}, {'$set': {'toggle': True}})
                    await ctx.send('Modlog has been turned on')```
vale wing
#

Wrong typehint

#

You set a default value, not a typehint

#
async def setmodlog(self, ctx, channel: discord.TextChannel = None)```
More correct
quick gust
stuck flare
#
 import discord 
from discord.ext import commands

client = commands.Bot(command_prefix=".")

@client.event
async def on_ready():
    print("I am online")

@client.command
async def ping(ctx):
    await ctx.send("Pong!")```
#

Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "ping" is not found

#

why is it not working

vale wing
#

No brackets for command decorator

stuck flare
#

yesh i forgot

vale wing
#
@client.command()```
stuck flare
#

ty

#

still not working

pallid mango
#
  @commands.command()
  async def temprole(self, ctx, member: discord.Member, role, duration:int):
    await member.add_roles(role)
    await ctx.send(f"{member.mention} has been given the {role} role for {duration}")
    await asyncio.sleep(duration)
    await member.remove_roles(role)
    await ctx.send(f"{member.mention} has been removed from the {role} role!")```
vale wing
pallid mango
#

Traceback (most recent call last): File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke await ctx.command.invoke(ctx) File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke await injected(*ctx.args, **ctx.kwargs) File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'id'

stuck flare
pallid mango
#

sorry to flood chat, could someone help me when they get time

#

thank you

vale wing
#

@pallid mango typehint role as well

pallid mango
#

wdym

stuck flare
#

@vale wing can u help

quick gust
#

did u restart your bot?

stuck flare
quick gust
quick gust
stuck flare
#

how do i turn it off in vs code

quick gust
#

close your terminal, at the top right of your terminal there will be a trashcan icon

#

click it and run the bot again

stuck flare
#

yes i see it

#

thanks it workd

quick gust
#

np

tacit token
#

hello guys, how can i make if the bot join to any server write hello

vale wing
#

!d discord.on_guild_join

unkempt canyonBOT
#

discord.on_guild_join(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild") is either created by the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") or when the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") joins a guild.

This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
tacit token
#

tyty

pallid mango
#
  @commands.command()
  async def temprole(self, ctx, member: discord.Member, role:discord.Role, time, duration:int):
    time_convert = {"s":1, "m":60, "h":3600,"d":86400}
    duration= int(time[0]) * time_convert[time[-1]]
    await member.add_roles(role)
    await ctx.send(f"{member.mention} has been given the {role} role for {duration}")
    await asyncio.sleep(duration)
    await member.remove_roles(role)
    await ctx.send(f"{member.mention} has been removed from the {role} role!")```
#

Traceback (most recent call last): File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke await ctx.command.invoke(ctx) File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 855, in invoke await self.prepare(ctx) File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 789, in prepare await self._parse_arguments(ctx) File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 697, in _parse_arguments transformed = await self.transform(ctx, param) File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 542, in transform raise MissingRequiredArgument(param) discord.ext.commands.errors.MissingRequiredArgument: duration is a required argument that is missing.

#

does anyone know the issue?

quick gust
#

.. you need to invoke the command with a duration aswell

pallid mango
#

idk how

vale wing
#

That weird time converter is here again bigflushed

#

Why not just use regex for time conversion

pallid mango
#

because i dont know how

quick gust
#

we are not that smart exen 😔

vale wing
#

I mean it's not that hard

#
r"\dm" #for mins
r"\dh" #for hours
#etc```
pine crown
#

lol

quick gust
#

i haven't even touched regex

vale wing
#

Understandable

#

Regex might be difficult to figure out but it is totally a useful feature

pallid mango
#

sooo

#

could someone help me understand lol 😢

tawdry perch
pine crown
#

he doesnt

pallid mango
#

no

quick gust
pallid mango
#

bruh

#

thats cool but in the mean timeee. 🥺

pine crown
#

🤣

pallid mango
#

nevermind, ill wait til tomorrow

tacit token
#
@client.event
async def on_guild_join(guild):
    general = find(lambda x: x.name == 'general',  guild.text_channels)
    if general and general.permissions_for(guild.me).send_messages:
        await general.send('Hello {}!'.format(guild.name))

Not work but nothing error code. c from discord.utils import find

manic wing
#

use get

maiden fable
#

Indeed

manic wing
#

and its get(iterable, name=…)

tacit token
#

and if i dont search the general

manic wing
#

it returns None

tacit token
#

and how

#

thanks

sullen surge
#

@vale wing thanks man turns out the html api a million times easier and everything works now 🙂

vale wing
#

Glad to help

pine crown
#
@client.command()
async def temprole(ctx, member: disnake.Member, role:disnake.Role, time):
  time_convert = {"s":1, "m":60, "h":3600,"d":86400}
  times = int(time[0]) * time_convert[time[-1]]
  await member.add_roles(role)
  await ctx.send(f"{member.mention} has been given the {role} role for {times}")
  await asyncio.sleep(times)
  await member.remove_roles(role)
  await ctx.send(f"{member.mention} has been removed from the {role} role!")

why for the seconds i am only able to put the seconds from 1-10? if i go above that, e,g i put 25s it makes it as 2s

quick gust
#

use regex as Exen said

pine crown
boreal ravine
slate swan
#

Is it possible to find out who deleted the user's message? (on_message_delete)

#

Hey, Simone knows how can I do the mobile online status?

#

It’s not in the api refreshes

maiden fable
unkempt canyonBOT
#

async for ... in audit_logs(*, limit=100, before=None, after=None, oldest_first=None, user=None, action=None)```
Returns an [`AsyncIterator`](https://discordpy.readthedocs.io/en/master/api.html#discord.AsyncIterator "discord.AsyncIterator") that enables receiving the guild’s audit logs.

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

Examples

Getting the first 100 entries:

```py
async for entry in guild.audit_logs(limit=100):
    print(f'{entry.user} did {entry.action} to {entry.target}')
```...
maiden fable
#

Gotta use this

slate swan
#

Okay

fervent shard
#
@bot.command()
@commands.has_permissions(administrator=True)
async def update (ctx, member: discord.Member):
  unverifiedRole = discord.utils.get(ctx.guild.roles, name="unverified")
  await ctx.author.remove_roles(unverifiedRole)

  verifiedRole = discord.utils.get(ctx.guild.roles, name="member")
  await ctx.author.add_roles(verifiedRole)```anyone know why this doesnt work? i use it as "+update {member}" and it doesnt send anything nor update the member i mentioned
#

?

slate swan
#

Nvm

slate swan
slate swan
digital barn
#

when can i start making discord bots? after mastering beginner/intermediate or advanced py?

slate swan
# fervent shard yeah

Does the command get executed? Try adding print statements on each step to debug it

slate swan
digital barn
#

ty

slate swan
#

if you are ready to push yourself in learning things you can start it as a beginner with basic python knowledge too

fervent shard
slate swan
slate swan
fervent shard
#

and no errors ^^

slate swan
#

do you have an on_message event?

slate swan
slate swan
fervent shard
slate swan
#

Tnx bro!

slate swan
#
ctx = commands.Context
m = SomeCommands.embeded_message()
m()

Getting this error message: TypeError: 'coroutine' object is not callable
sys:1: RuntimeWarning: coroutine 'Command.call' was never awaited
function looks like this:

        
        embed = discord.Embed(title='productname', url="https://test.com", colour=0x87CEEB, timestamp=datetime.utcnow())
        await ctx.send(embed=embed)```
fervent shard
tender estuary
slate swan
#

!d discord.Guild.get_role

unkempt canyonBOT
slate swan
slate swan
#

not by calling it thru a function

slate swan
misty quest
#

Is there a way to generate a discord link to authorize bot and when user agrees some role is given?

dry kelp
#

https://mystb.in/ConsecutivePromotesCookies.python

What the code should do is reset the guild vanity url if it was changed

What does it do so far?
Bans the member and sends the log if the log channel is set

What should it do?
Set the guild vanity code to the before url code

What's ur issue?
I can't get the before-after url code

#

before.vanity_invite.code pretty sure this has no atr

#

or it does but it won't work

kindred drum
#

    @commands.command(name="stats")
    async def stats(self, ctx, member: discord.User, full=None):
        
        with open("./all_user_rep.json") as inf:
            data = json.load(inf)
            
            for i in range(0,len(data)): #It doesn't exist
                for x in data[i]:
                    print(x)
                    if int(x) == int(member.id):
                        if full == True:
                            print("yes")
                        else:
                            print(data[i][x])
                            await ctx.send(str(data[i][x]["Payment Method"])+str(data[i][x]["Discord_Name"]) + str(member.id)+str(data[i][x]["rep_amount"]))
                        ``` how do I add a condition so that if they add "full" to the command, it runs "yes"
slate swan
#

Is it possible to find out who deleted the user's message? (on_message_delete)

slate swan
#

Okay , wait

vale wing
kindred drum
#

nvm i got it

kindred drum
#

o i see

vale wing
#

Only in that case

slate swan
kindred drum
slate swan
#

Go dm

scarlet aurora
#

hey guys, i want to make it so that when you input the bots token via console, it stores it in a json file for further use, how would I do this?

slate swan
#

Is it possible to find out who deleted the user's message? (on_message_delete)

grand hazel
#

Make a file name data.json

scarlet aurora
#

thanks

#

i already made a file named config.json

grand hazel
#

Change the filename then

scarlet aurora
#

yeah ok

#

how do i call the token in the json file?

slate swan
#

Helpp

nimble plume
#

hecl

slate swan
vale wing
slate swan
#

json.dump(dict , file)

grand hazel
scarlet aurora
#

i mean how do i retrieve from data.json

grand hazel
#

Wait k

#

filename = "data.json"
with open(filename, 'r') as file_object:
data = json.load(file_object)
print(data)

slate swan
#

What?

grand hazel
#

It seems so illegal without ‘’’

scarlet aurora
#

ty

slate swan
#

Can't this be done...?

scarlet aurora
vale wing
#

!d discord.Guild.audit_logs @slate swan this only

unkempt canyonBOT
#

async for ... in audit_logs(*, limit=100, before=None, after=None, oldest_first=None, user=None, action=None)```
Returns an [`AsyncIterator`](https://discordpy.readthedocs.io/en/master/api.html#discord.AsyncIterator "discord.AsyncIterator") that enables receiving the guild’s audit logs.

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

Examples

Getting the first 100 entries:

```py
async for entry in guild.audit_logs(limit=100):
    print(f'{entry.user} did {entry.action} to {entry.target}')
```...
scarlet aurora
#

im hosting on my pc

grand hazel
#

Did u put ur token on env

#

Oooo

vale wing
#

You can't determine who deleted user's message without audit logs

grand hazel
#

Just client.run(‘ehichsjchsicgcosgxidh’)

scarlet aurora
#
with open(filename, 'r') as file_object:
  data = json.load(file_object)
print(data)```
slate swan
#

I dont understand

#

🤔

vale wing
#

Read the docs

slate swan
#

Okay

scarlet aurora
#
filename = 'config.json'
with open(filename, 'w') as file_object:
 json.dump(token, file_object)``` @grand hazel so like this?
vale wing
scarlet aurora
#

?

grand hazel
scarlet aurora
#

i'm trying to make it so that i can input my bots token

#

i want to automate it

slate swan
#

what's the point of inputting bot token/

#

just bot.run('token')

scarlet aurora
#

cuz i want to distribute it

#

and i don't want MY token in it

grand hazel
grand hazel
scarlet aurora
#

yes

slate swan
#

ask them to create an env file themselve

grand hazel
#

Then just

vale wing
#

Env > json in terms of storing token

scarlet aurora
#

so everytime i run the file, i want it to fetch from config.json the TOKEN they inputed last time

grand hazel
#

Token = input(“token : )
Bot/client.run(Token

vale wing
#

Or you can even encrypt it sillySmile

scarlet aurora
#

YES

vale wing
#

Idk what tf for but I always encrypt my tokens

grand hazel
#

Token = config.get("Token")

#

Then bot.run(Token)

vale wing
#

Yeah

#

Have you checked?

#

If you can't find it I can screenshot for you

scarlet aurora
#

@grand hazel but this is the config file

#

it just has the token there

grand hazel
vale wing
grand hazel
scarlet aurora
#

where do i put that

vale wing
#

Yeah

#

+5 user +5 message

#

Kinda stupid that discord is forcing us to migrate to slash commands and they put limit to those

scarlet aurora
#

@grand hazel so how do i make it overwrite token = input when the token is already in config.json

vale wing
#

I will have to scam them for message content intent LMAO

grand hazel
vale wing
#

Yeah

scarlet aurora
#

@vale wing

#

i need help

vale wing
#

@scarlet aurora so you want to store the token in json file?

scarlet aurora
#

i want it to overwrite the token = input when there is an existing token in config.json

solar ridge
#

If you wont use the stored token and overwrite it everytime then why are you storing it

scarlet aurora
#

?

#

the first time i run the programme, it asks me to input a token

#

then stores in json

#

everytime other time it wont ask me for input, it just uses the token in config

vale wing
#

First, create a file config.json or whatever you would like to name them

Next, this is how you fetch the json dictionary from file

import json

with open('config.json', 'r') as f:
    config = json.load(f)```

You will have the contents of json file in dictionary format in your `config` variable. You can operate with it as with any dict.

After you completed required operations, just overwrite the file with the modified dict
```py
with open('config.json', 'w') as f:
    json.dump(config, f)```
tender lily
#

Is it possible to copy an embed by Id and get same embed paste in other server

dire folio
#

Can bots make these events

vale wing
vale wing
vale wing
#

You can just send the same embed object to somewhere?

tender lily
#

Yss

#

How

vale wing
#

You mean how to get it from a message right?

tender lily
#

Any bot their for it

tender lily
scarlet aurora
#

@vale wing i made it so that it stores it in config.json but i don't understand how to make it so that it wont ask me for input next time

vale wing
#

!d discord.Message.embeds just get the first element

unkempt canyonBOT
vale wing
#

Or check the len

tender lily
scarlet aurora
#

do i do this before the input or after

vale wing
vale wing
scarlet aurora
#
NameError: name 'config' is not defined```
vale wing
#

You didn't understand it seems 🙁

scarlet aurora
#

😦

scarlet aurora
#

i did create the config.json file

#

and i made it so that it stores the input in there

vale wing
#

First you need to fetch file's content

slate swan
vale wing
scarlet aurora
#
with open('config.json', 'w') as f:
    json.dump(config, f)
if config['token'] != '':
    ...```
vale wing
#

It has most of the attributes context has

scarlet aurora
#

so like this?

slate swan
vale wing
scarlet aurora
#
with open('config.json', 'r') as f:
    config = json.load(f)
if config['token'] != '':
    ...```
#

so like this?

vale wing
scarlet aurora
#

ok, so if statement, i want it to go pass the input

#

how do i do that

vale wing
#

Make sure there's a "token" key in your json file

scarlet aurora
#

it just has "" in json file

vale wing
#

Fill it in

scarlet aurora
#

ofc the token in it

#

"example.token.3rrdswsg"

vale wing
#
{
    "token": ""
}```
scarlet aurora
#

oh ok

#

so how do i make it so that the if statement goes past the input option if config.json = token

#

should i put the input into a function and only call it when there is no token in config?

#

or is there an easier way

vale wing
#

Yeah you can make a function if you want

slate swan
vale wing
scarlet aurora
#
with open('config.json', 'r') as f:
    config = json.load(f)
if config['token'] != '':
    token = token
def token():
    token = input(pyfade.Fade.Horizontal(pyfade.Colors.col, f"Input Token: "))
filename = 'config.json'
with open(filename, 'w') as file_object:
 json.dump(token, file_object)``` so like this?
dusty tapir
slate swan
vale wing
vale wing
unkempt canyonBOT
#

class discord.Message```
Represents a message from Discord.

x == y Checks if two messages are equal.

x != y Checks if two messages are not equal.

hash(x) Returns the message’s hash.
scarlet aurora
#

basic stuff

vale wing
#

Like?

scarlet aurora
#

like functions, arrays, input out

#

put

vale wing
#

That should be enough

scarlet aurora
#

if, else, for and stuff

slate swan
dusty tapir
#

if someone have problem by opening config.json files,
i can explain how to fix it.

scarlet aurora
#
with open('config.json', 'r') as f:
    config = json.load(f)
if config['token'] != '':
    token = token
def inputtoken():
    token = input(pyfade.Fade.Horizontal(pyfade.Colors.col, f"Input Token: "))
filename = 'config.json'
with open(filename, 'w') as file_object:
 json.dump(token, file_object)``` so is this better @vale wing ?
vale wing
#

Builitin bans can't be automatically timed

dusty tapir
slate swan
#

its faster to type out stuff quickly, and no i disagree that discord's implementation are good, the slash commands are too slow on phone and some of them are not even out yet

vale wing
#

I mean you can't provide time to discord and let the discord itself unban the user at certain time. You need a bot with tempban command

scarlet aurora
#
with open('config.json', 'r') as f:
    config = json.load(f)
if config['token'] != '':
    token = token

def inputtoken():
    token = input(pyfade.Fade.Horizontal(pyfade.Colors.col, f"Input Token: "))

filename = 'config.json'
with open(filename, 'w') as file_object:
 json.dump(token, file_object)``` can u just tell me whats wrong here @vale wing and what i need to add or remove
slim ibex
#

you trying to load your token from JSON?

vale wing
slate swan
scarlet aurora
vale wing
#

I mean wtf is that lol

scarlet aurora
#

that was just an example, because i was asking u what the if statement should be to skip over the input if there is a token in config.json

slim ibex
#

why store token in json? store in .env file

dusty tapir
#
# imports
import os
import json


def check():
    if os.path.exists("../config.json"):
        with open("../config.json", encoding="utf-8") as infile:
            token = json.load(infile)
            return token['bot_token']

i hope that fix the problem for you

vale wing
#

Your function should return the entered token

scarlet aurora
#

so token = token?

dusty tapir
# slate swan show the real code/issue, not the repo
@bot.command()
@has_permissions(manage_messages=True, manage_roles=True)
async def mute(ctx,user: discord.Member, reason):
    perms = ctx.channel.overwrites_for(user)
    await ctx.channel.set_permissions(user, send_message=not perms.send_message)
    await ctx.send("muted the " + str(user.nick) + " !")```
this won't worked for me
dusty tapir
vale wing
#

This is aids

slate swan
heavy folio
unkempt canyonBOT
#

await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sets the channel specific permission overwrites for a target in the channel.

The `target` parameter should either be a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that belongs to guild.

The `overwrite` parameter, if given, must either be `None` or [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite"). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions") attributes. If this is done, then you cannot mix the keyword arguments with the `overwrite` parameter.

If the `overwrite` parameter is `None`, then the permission overwrites are deleted.

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

thanks

heavy folio
#

override the perms variable, send_messages = False

#

then update overwrites to be that

unkempt canyonBOT
#

src/Client.py lines 53 to 56

@mute.error
async def mute_error(error, ctx):
    if isinstance(error, CheckFailure):
        await bot.send_message(ctx.message.channel, "Looks like you don't have the perm.")```
dusty tapir
slate swan
#

cause the check function is inside a folder

#

and config.json is not

vale wing
#

Nothing seems bad

dusty tapir
#

i want to mute the user from all channels

#

not one channel

vale wing
#

Once again, you can't provide ban time to discord

slate swan
#

The ui doesn't provide tempbans

#

Which is preferred widely

vale wing
#

Reading something from audit might take a while

#

It is better and faster to store the unban time and unban once it comes

vale wing
slate swan
#

exactly

#

You can't even add roles to a person who has any role above you on phone.

vale wing
#

That's weird as well

#

Discord actually had issues with mentions on mobile that's what I hated the most

slate swan
#

nope, it works on desktop

vale wing
#

Iterating through all the audit logs will take a while because of the ratelimit

slate swan
#

/ban?

vale wing
#

How do you suggest to do it then?

#

I mean literally

#

I know what an audit is

slate swan
#

:^) Funny how a user and bot account uses the same api but ways to do things are different?

slate swan
# vale wing Well, you can use `msg.channel.send`

Need a little more context can't figure out how to use "msg" part for the command i used this bot = commands.Bot(command_prefix="!")
should create something like this for the message as well right?

vale wing
#

@slate swan I mean how would you get an audit action that was done let's say 2 weeks ago?

#

Show the code

#

I can only think of iteration which is slow

#

The method of unbanning is weird

timid wagon
#

The method of unbanning aside, that will also be unreliable - seeing the amount of requests you would be making

tacit token
#

hello guys i created an owner only command. How can i use error but the member not the owner? idk -> member u not the owner

slate swan
#

if you try to add/remove multiple roles at the same time it gets messy

vale wing
#

That's why you need custom ban command

timid wagon
#

You can't just use guild.audit_logs() here, because you're checking for an entry made a certain amount of time ago

vale wing
#

Ah you mean put it into the reason

vale wing
#

No invalid input handling

slate swan
vale wing
#

Not good as well, it is better to make custom ban command still

vale wing
#

Alright alright, let's end this discussion

#

It is really personal lol

quick gust
#

Not many great free hosts but AWS has a free tier

dire folio
timid wagon
#

replit and aws are worlds apart, so no

#

replit makes it pretty clear while you're running the keep_alive server, that it is not to be used in prod and should not be used 24/7

#

Basically confirms its not meant for your bot hosting needs. Keeping the server with uptimerobot is a workaround people found.

#

AWS is secure, aims to have minimal downtime, and has servers built with the assumption that they'll work with heavy workload.

slim ibex
#

vultr but it isn;'t free

timid wagon
#

And yeah, at this point I would recommend checking the pins in this channel

#

^

slate swan
timid wagon
#

It includes the person who deleted this message. You would ideally check the audit logs inside the event itself

slate swan
#

done but not right

timid wagon
slate swan
#

Go dm

#

?

novel bolt
#

hey , is there a way to play tempfile in vc?

#

i just came to know abt tempfile now only, the code i made runs but voice doesnt come from the bot, but it gives no errors too

honest vessel
#

i want to pass a string as date like 2022-02-02 02:02:02 and then a reason that can contains spaces, how can i accept the date to let 1 space be in it?

stuck flare
honest vessel
#

i have something like this now, ```py
async def timeout(self, ctx, member: Member, *, until: Optional[Union[str, datetime]], duration: Optional[Union[float, timedelta]]=None, reason=None) -> None:

slate swan
timid wagon
#

You're taking in both the date and time, right?

honest vessel
#

@timid wagonyeah but then reason dosnt allow spaces cause i use *,

timid wagon
#

The simple way to do it would be to take date and time separately, and then use * for the rest of the reason

honest vessel
#

ah

timid wagon
#

You can later join the date and time strings

honest vessel
#

ah yeah i didnt think of that xD

#

thx

timid wagon
#

Yep

stuck flare
slate swan
#

what makes it bad? other than you not getting spoonfeeded

timid wagon
#

The quality of the guide depends on how you utilize what is says mmlol

quick gust
#

😐

tacit storm
#

you're not gonna learn by looking at videos mainly.

slate swan
#

*i dont want to read what it says

tacit storm
#

a big thing about programming is reading

slim ibex
#

^^^

#

100% agree

tacit storm
#

if you're gonna just push of the reading part of programming, you should not be programming, none the less using discord.py

slim ibex
#

you'll have to read docs for tons of things

slate swan
#

you'll keep following tutorials and using their code, but you wont get a single part they are doing.

tacit storm
#

^^

slim ibex
#

so yeah, reading is crucial to programming

tacit storm
#

in short, read or get out Troll

slim ibex
#

mhmm

#

🗿 moai agrees

stuck flare
#

kk srry

simple cypress
#

What's this error?

slim ibex
#

tf

tacit storm
#

jeez thats low quality

slim ibex
#

android moment

final iron
tacit storm
#

ive never seen that error before actually.

slate swan
#

Why when someone deletes a message, it says that I deleted it, but I did not delete it. (on_message_delete)

slate swan
#

Someone deletes his message, and in the logs he writes like I deleted it, how to fix it?

slim ibex
#

code

#

show code

tacit storm
#

gve us the code or we cant help.

slate swan
#

Okay

#

@bot.event
async def on_message_delete(message):
    guild = message.guild
    async for entry in guild.audit_logs(limit=1, action=discord.AuditLogAction.message_delete):
        print(f'{entry.user} did {entry.action} to {entry.target}')
    channel = bot.get_channel(935160414965211179)
    emb=discord.Embed(title="Удаленное сообшение", description="**__Информация:__**", color=discord.Color.from_rgb(255, 0, 0), timestamp=message.created_at)
    emb.set_footer(text="© Все права защищены The Greatest", icon_url=message.author.avatar_url)
    emb.add_field(name="**Участник:**", value=f"**{message.author.name} ({message.author.mention}) **", inline=False)
    emb.add_field(name="**Удаленное сообщение:**", value=f"`{message.content}`", inline=False)
    emb.add_field(name="**Удалил:**", value=f"{entry.user}", inline=False)
    emb.add_field(name="**Канал • ID:**", value=f"**<#{message.channel.id}>** • **{message.id}** ", inline=False)

    await channel.send(embed=emb)
tacit storm
#

Ah

#

it's saying that because it's fetching it from the audit logs

#

i think thats the reason it's saying you deleted it

#

(correct me if im wrong)

slate swan
#

How to fix?

slim ibex
#

is there a property for someone that deletes a message?

slate swan
slim ibex
#

or something like that

#

yeah i thought sop

slate swan
#

Helpp

slate swan
slim ibex
#

i don't think what you want to do can be done @slate swan

#

you are trying to get the person who deleted the message correct?

slate swan
#

Yes

slim ibex
#

ye unfortunately it doesn't seem like you can do that

slate swan
#

Yeap(

#

so how do i fix it?

final iron