#discord-bots

1 messages Β· Page 275 of 1

slate swan
#

also if you want to annotate a argument you use :

#

guild: discord.Guild like this

buoyant quail
#

it's isinstance

timid spade
#

it worked, thanks man

cloud dawn
slate swan
buoyant quail
#

The question is why didn't that if work

slate swan
#

the other question is why in else you assign id as guild object

#

if its not guild i would just return or raise

past obsidian
#

And so what to do?

buoyant quail
#

Debug πŸ˜„

slate swan
#

you dont pass guild object to the function

buoyant quail
#

print(isinstance(guild, discord.Guild), guild) is what i'd do first

#

to see that it actually doesn't work

past obsidian
#
    print(isinstance(guild, discord.Guild), guild)
                     ^^^^^
NameError: name 'guild' is not defined```
cloud dawn
#

Has to be in the scope of the function.

slate swan
past obsidian
#

so?

slate swan
#

put it at the top

buoyant quail
#

The error will come faster

cloud dawn
#

Well this is interesting

#

Guild is a Hashable class, meaning when imported it's not identical when imported in init.

#

isinstance(guild, discord.guild.Guild) Would most likely work.

past obsidian
buoyant quail
buoyant quail
sick birch
#

What's the point of isinstance(guild, discord.Guild)? Shouldn't it always be a discord.Guild?

past obsidian
#

Sorry

cloud dawn
#

I wouldn't recommend MongoDB for a Python project anyways xd

#

Mongo is great for js and ts tough.

sick birch
#

Eh, it's more about the nature of the data you're be dealing with rather than the language if you ask me

sick birch
#

I think Discord fundamentally lends itself well to a relational database format, so still, I'd recommend SQL over NoSQL when working with Discord-related stuff

cloud dawn
#

That really depends on the bots size tough.

past obsidian
#

I am getting that error after running this code ```py
@bot.command(aliases=['Casino', 'казино', 'Казино'])
async def casino(ctx, count=None):
user = check_user(ctx.author.id, ctx.guild)
if not count:
return

try:
    count = int(count)
except ValueError:
    await ctx.send(embed=discord.Embed(title="Ошибка", description="НСкоррСктноС Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅ ставки", color=discord.Color.red()))
    return

currency = get_currency(ctx.guild)

if count >= 10:
    if user['balance'] - count >= 0:
        times = user.get('times', {})
        last_beer_time = times.get('beer', dt.utcnow() - timedelta(seconds=600))
        total_seconds = (dt.utcnow() - last_beer_time).total_seconds()

        rand = random.randint(1 if total_seconds < 600 else 10, 100)

        if rand <= 77:
            rand = -1
        elif rand > 77 and rand <= 92:
            rand = 2
        elif rand > 92 and rand <= 99:
            rand = 3
        elif rand > 99:
            rand = 10```
#

Maybe it will give something

past obsidian
#

.

twilit grotto
#

that is the code, not an error

past obsidian
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: InvalidDocument: cannot encode object: <Guild id=1065340260957044797 name='Ukraine Community' shard_id=0 chunked=False member_count=4>, of type: <class 'discord.guild.Guild'

formal basin
#

Is a way to use a loop but using time instead of a countdown?

past obsidian
#

Wow I managed to fix it myself

sick birch
sick birch
#

!d discord.ext.tasks.loop

unkempt canyonBOT
#

@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, name=None)```
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").
slate swan
#

might swap it out with aiohttp + mongo data api if I can be bothered

timid spade
#

using the get_guild function of discord.Client is the only was to get discord.Guild from a guild id right?

sick birch
#

And if you want to get a guild from ID that's the method you should use

timid spade
timid spade
sick birch
#

You should pass the guild into the function then

#

If you're passing in ID, it shouldn't be much harder to pass in a guild

timid spade
#

it's a bit complicated, I will try to explain simply.
there is a function I am working on and there is another function which returns some data from an sql file about a guild. but that function takes guild object instead of Id and I have to use that function in the function I am working on.
a bit messy but yes I need guild object from id

timid spade
#

also @sick birch when did you start working on discord.py lib

sick birch
#

What do you mean?

#

I haven't really "worked" on discord.py, I've only contributed some examples

timid spade
#

yes, I am sorry, with I mean

#

idk it's been a while I am using this and still there are things that are completely out of my mind

sick birch
#

a few years at this point

timid spade
#

maybe it's my first library of first language I learned

timid spade
sick birch
#

But this is more general Python stuff rather than discord.py specific stuff

timid spade
#

that's cool

sick birch
#

But to answer your question - you need to pass around the client object wherever you need it, as arguments to functions

timid spade
dusk pumice
#

Can I get user with id?

#

Not using ctx.author

upbeat gust
unkempt canyonBOT
#

get_user(id, /)```
Returns a user with the given ID.

Changed in version 2.0: `id` parameter is now positional-only.
dusk pumice
#

Thank you

timid spade
#

my code was working fine last night but now i cant even import

error: ImportError: cannot import name 'commands' from 'discord' (C:\Users\wodgenzi_\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\__init__.py)
buoyant quail
#

You are magician if it was working

#

Because that errors says truth - there is no commands inside discord

#

It is in discord.ext

slate swan
timid spade
#

i reinstalled visual studio code and its fixed now

slate swan
timid spade
#

and yeah its like this since forever

timid spade
slate swan
#

!e from numpy import something

unkempt canyonBOT
#

@slate swan :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     from numpy import something
004 | ImportError: cannot import name 'something' from 'numpy' (/snekbox/user_base/lib/python3.11/site-packages/numpy/__init__.py)
timid spade
#

i dont have previous error message cuz new IDE
otherwise i would have checked the exact error

slate swan
#

you had to got this from somewhere

timid spade
#

by exact error i mean
the whole text, not just the last time error name

slate swan
#

full traceback wouldnt actually change anthing

#

this import wouldnt occur in source code

timid spade
#

the error was in this file and these are the import lines, idk man

buoyant quail
#

I'd believe it was not saved

buoyant quail
timid spade
#

yes maybe, i thought that too but i am pretty sure that i made no changes

#

i assuming a change got reverted by reinstalling IDE, how that happened? i dont know

slate swan
#

if you didnt save a file could be

#

but i belive when closing ide it should warn you that you have unsaved changes

timid spade
timid spade
slate swan
#

what ide?

timid spade
#

like it shows this dot when unsaved and i am closing it and its not giving a warn

timid spade
slate swan
#

visual studio or visual studio code?

#

those are two things

timid spade
#

saved is like this

#

un saved

slate swan
#

based on screenshot visual studio code

timid spade
#

yep

slate swan
#

thats why i use autosave

timid spade
#

it has a built-in or extension?

slate swan
#

built in

#

just search auto save

timid spade
#

found it

#

what does it mean by after delay?

slate swan
#

that it wont save on each character you type

#

but after a little break of typing

#

in simple terms

timid spade
#

wow, how i never knew about it

slate swan
#

for example i also disable Enable Preview option

#

so it opens in normal mode

timid spade
slate swan
#

yeah

timid spade
#

i dont know whats the normal mode but anyway i am still disabling it

slate swan
#

you might notice that when you open a file it shows up with cursive name

#

and when you type something in it is in normal text

#

the cursive is preview

timid spade
#

oh, yeah

slate swan
#

i got it like this

timid spade
#

found it

slate swan
#

enabled cause i dont code on windows 🀭

timid spade
#

i tried linux but i thin i didnt install it correctly

#

it suddenly stopped working

slate swan
#

im not using linux either

timid spade
#

then?

#

mac?

slate swan
#

macos

timid spade
#

is it any better while coding or just as same as windows?

slate swan
#

way better

#

at least for me

vocal snow
timid spade
timid spade
#

anyone know how can i pass the client variable to another file?

slate swan
#

use cogs

timid spade
# slate swan use cogs

if i make the class a cog then functions in it will become useable by discord users.
the functions where i need client variable are just for my use in code. they are used to fetch data from data base

buoyant quail
#

But yeah, for custom functions you can use just a normal class/functions, no need a cog

timid spade
buoyant quail
#

Just pass the bot in its constructor/arguments. Same as for cogs

buoyant quail
#
def my_function(bot):
    ...

my_function(bot)

or

class MyClass:
    def __init__(self, bot):
      self.bot = bot

... = MyClass(bot)

or something else, depends on how you want it to be

slate swan
timid spade
timid spade
#

i just noticed, a function in a class was working fine without the self parameter, anyone know how that happened?

buoyant quail
#

You didn't make an instance maybe

#

Or you did make it static but i guess you didn't

timid spade
#

this is how i am using it

#

this is how i definied it

buoyant quail
timid spade
buoyant quail
#

like that

timid spade
#

i guess, i am gonna take another python course then start again

#

i have some uncleared concepts about async, decorators and OOPs

buoyant quail
#

wow
i don't often see such people here

#

usually here are "i have no idea what i am doing i will just do something random and keep asking"

timid spade
#

its just i learned python from an indian guy on youtube, now i saw there are harvard CS50 lectures too

timid spade
#

and thats kinda frustrating when errors pop up

cloud dawn
#

Not that the Harvard lectures are hard lmao

#

They go in to depth too much for my taste

harsh orbit
#

Why when I put more than one argument in command it only reads the first one and when I run the command it's telling me that missing assignments that I already put them

#

Please any on help me

buoyant quail
#

Maybe you did put a star..

#

Show the code

harsh orbit
#

I tried with and without the star

#

And it's the same

#
async def bc(ctx, member,  message,* ,user: discord.Member):
#
async def bc(ctx, member,  message, user: discord.Member):
buoyant quail
#

And how are you calling it?

harsh orbit
#

hah?

buoyant quail
#

The message

#

like !bc abc 123 hello

harsh orbit
#

Yup

#

Like this

buoyant quail
#

show it exactly

harsh orbit
#

.bc hello

buoyant quail
#

You are asking for member, message and user

#

Here you gave only one argument member

harsh orbit
#

I will show you the command code

#

@bot.command()
async def bc(ctx, member,  message, user: discord.Member):
  guild = ctx.guild()
  count = 0
  for member in guild.memebrs:
    if member.bot:
      pass

    elif member.status is not discord.Status.offline:
      try:
        await user.send(message)
        count += 1

      except:
          pass
    else:
      pass

  embed = discord.Embed(title="Brodcast", description="Brodcast info")
  embed.add_field(name="Messages", value=count)
  await ctx.reply(embed=embed)
buoyant quail
harsh orbit
#

What

buoyant quail
#

Looks like you don't understand what you are doing :/

harsh orbit
#

Why

buoyant quail
#

Calling attribute with brackets, Adding multiple pass and conditions that are doing absolutely nothing, Calling with one argument and expecting to get 3

#

What are member and message for? You are not using them. And you aren't giving

harsh orbit
buoyant quail
#

Spamming online people

harsh orbit
#

message for set the message to send

buoyant quail
#

Ye. Actually it has some use, but if you don't do something inside if just change the second condition

Also

else:
   pass

That surely does nothing

harsh orbit
#

So I will remove

buoyant quail
harsh orbit
#

You didn't answer me

buoyant quail
#

I guess you want to keep only message

#
@bot.command()
async def bc(ctx, message):
#

And send message not to the same user, but to each member once

await member.send(message)
harsh orbit
#

Wait

buoyant quail
harsh orbit
#

._.

buoyant quail
#

It's saying about line user = discord.Member()

harsh orbit
buoyant quail
#

But you have guild = ctx.guild() which is also wrong
It's not a method, just an attribute. No need to call it

harsh orbit
#

I will try something and show you

#

@bot.command()
async def bc(ctx, message):
  message = discord.Message()
  count = 0
  for member in guild.memebrs:
    if member.bot:
      pass

    elif member.status is not discord.Status.offline:
      try:
        await member.send(message)
        count += 1

      except:
          pass
    else:
      pass

  embed = discord.Embed(title="Brodcast", description="Brodcast info")
  embed.add_field(name="Messages", value=count)
  await ctx.reply(embed=embed)
#

correct?

buoyant quail
#

remove message = discord.Message()

harsh orbit
#

I forgot

buoyant quail
#

add guild = ctx.guild or change loop to for member in ctx.guild.members:

harsh orbit
#

I know it wrong

harsh orbit
#

Can I replace
ctx.guild with guild id?

buoyant quail
#

You can use get_guild function to get guild by id

harsh orbit
#

Ok

#
bot.command()
async def bc(ctx, message):
  count = 0
  for member in guild.memebrs:
    if member.bot:
      pass

    elif member.status is not discord.Status.offline:
      try:
        await member.send(message)
        count += 1

      except:
          pass
    else:
      pass

  embed = discord.Embed(title="Brodcast", description="Brodcast info")
  embed.add_field(name="Messages", value=count)
  await ctx.reply(embed=embed)
        ```
#

Guild = discord.get_guild()

#

And Id in ()

buoyant quail
#

Not discord

harsh orbit
#

What

buoyant quail
#

It's not discord method

harsh orbit
#

There is a change

#

ctx.guild.mebers
In for

#

Like you said

buoyant quail
#

meme bers
i copied it from you :p

#

it's members

harsh orbit
#

Sorry for that πŸ˜…

#

Finally it worked

#

Thx for help

plucky sun
#

how to add server emoji in button

#

?

buoyant quail
#

!d discord.ui.button

unkempt canyonBOT
#

@discord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.

The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View"), the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") you receive and the [`discord.ui.Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button "discord.ui.Button") being pressed.

Note

Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button "discord.ui.Button") manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
buoyant quail
#

just pass emoji argument

harsh orbit
#

What is this

harsh orbit
#

...

wispy pasture
#

can choices have space in ther text??? like ai model space between ai and model

naive briar
#

Just try it

naive briar
#

You're probably spamming something to the API

harsh orbit
#

This thing only on repl it

buoyant quail
#

Replit
While this may seem like a nice and free service, it has a lot more caveats than you might think, such as:

  • The machines are super underpowered.
    • This means your bot will lag a lot as it gets bigger.
  • You need to run a webserver alongside your bot to prevent it from being shut off.
    • This isn't a trivial task, and eats more of the machines power.
  • Repl.it uses an ephemeral file system.
    • This means any file you saved via your bot will be overwritten when you next launch.
  • They use a shared IP for everything running on the service.
    This one is important - if someone is running a user bot on their service and gets banned, everyone on that IP will be banned. Including you.
#

The last one is your case

naive briar
#

Eh, I don't think so; looking at their code

bot.command()
async def bc(ctx, message):
  count = 0
  for member in guild.memebrs:
    if member.bot:
      pass

    elif member.status is not discord.Status.offline:
      try:
        await member.send(message)
        count += 1

      except:
          pass
    else:
      pass

  embed = discord.Embed(title="Brodcast", description="Brodcast info")
  embed.add_field(name="Messages", value=count)
  await ctx.reply(embed=embed)
        ```
> [#discord-bots message](/guild/267624335836053506/channel/343944376055103488/)

It's most likely because they're sending messages to every member of a guild
gilded depot
#

I amtrying to make a levelling system. Here's my code:

@client.event
async def on_message(message):
   print(message.author.id)
   user = message.author.name
   if message.author.bot:
      print("Nevermind guys!")
      return
   else:
      await message.channel.send(user)
      async with aiosqlite.connect("stuff.db") as db:
           async with db.cursor() as cursor:
               await cursor.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER UNIQUE, guild INTEGER UNIQUE, xp INTEGER, level INTEGER)")
               await cursor.execute("INSERT OR IGNORE INTO users (id, guild, xp, level) VALUES (?, ?, ?, ?)", (message.author.id, message.guild.id, 1, 1))
               if cursor.rowcount == 0:
                   await cursor.execute("UPDATE users SET xp = xp + 1 WHERE id = ? AND guild = ?", (message.author.id, message.guild.id))
                   await db.commit()

               await cursor.execute("SELECT xp, level FROM users WHERE id = ? AND guild = ?", (message.author.id, message.guild.id))
               row = await cursor.fetchone()
               xp = row[0]
               level = row[1]

               exp = 5 * level**2 + 10 * level + 100
               new_level = int(math.sqrt(xp / 5 + 10) - 1)

               if new_level > level:
                   await message.channel.send("Level Time!")
                   level = new_level
                   await cursor.execute("INSERT OR IGNORE INTO users (id, guild, xp, level) VALUES (?, ?, ?, ?)", (message.author.id, message.guild.id, xp, new_level))
                   print(level)
               await db.commit()

      if message.content == "c!hello":
         await message.channel.send("Hello. Hope all is well.")

When I run it there are no errors but it isnt properly updating the table:
Ive uploaded an image:
as u can see its alternating between 1 and 2 for the level and nothing changes with xp. Please help! whats wrong. HELP!

vale wing
#

When the

#

Ok let's take a look

vale wing
# gilded depot I amtrying to make a levelling system. Here's my code: ```py @client.event async...

I haven't figured out what exactly is wrong with that thing yet but here are some recommendations

  1. You should only have one connection for bot. Example
class MyBot(commands.Bot):
    db: aiosqlite.Connection | None

    async def setup_hook(self):
        self.db = await aiosqlite.connect(...)

    async def close(self):
        await self.db.close()
        await super().close()
  1. Execute scripts for creating tables on setup stage, not when you need to access db
  2. I'm not aiosqlite expert but creating additional cursor seems obsolete, there's db.execute()
#

And I do think you confused var names in this block

xp = row[0]
level = row[1]

exp = 5 * level**2 + 10 * level + 100
new_level = int(math.sqrt(xp / 5 + 10) - 1)

Cause your exp variable is unused

#

Maybe you meant to use exp in new_level calculation

gilded depot
#

because it wont pick that up

naive briar
#

Pick what up

turbid condor
#

A question shouldn't the new_level be level+1?

thin raft
#

he's calculating the level according to the exp he has

#

wait I just understood what you meant

turbid condor
thin raft
#

yeah you're right

turbid condor
#

I don't see level being incremented

#

And i don't know what kind of dish is that new_level cooking

thin raft
#

oh wait

#

I just realised again, why would it be level + 1?

turbid condor
#

Like if the level that is retrieved in level variable is one so doesn't it need to be incremented?

thin raft
#

I think it doesn't

#

you have 100 xp

#

and talk and get 105xp, which is level 2

#

100xp -> Level 1
105xp Level 2

#

if you have more or equal than 105xp, the new_level would be 2

#

so level < new_leve would be true

turbid condor
#

Tbh i still didn't get it

#

Like as far as i can see the new_level is calculated based on current xp

thin raft
#

you are on level 3, and have 5 xp

#

when you talk and get 3 more xp

#

your last level (level) will be 3, but the new_level calculated with the past xp would be 4

turbid condor
#

So yeah how will the this 4 be changed in the db

thin raft
#

wdym

turbid condor
#

Like i don't know how that formula is working

thin raft
#

bot dead?

#

@unkempt canyon

turbid condor
#

!e

import math
lvl=int(math.sqrt(100/5+10)-1)
print(lvl)
unkempt canyonBOT
#

@turbid condor :white_check_mark: Your 3.11 eval job has completed with return code 0.

4
turbid condor
#

So 100 xp is equal to lvl 4

thin raft
#

!e

import math
lvl=int(math.sqrt(160/5+10)-1)
print(lvl)```
unkempt canyonBOT
#

@thin raft :white_check_mark: Your 3.11 eval job has completed with return code 0.

5
thin raft
#

tbh I would make a table for each level and xp needed

cloud dawn
#

Math scales a lot better.

turbid condor
#

Welp i would calculate the xp till next level and define it and then check the current xp with that
And when the user levels up increment the level by 1

thin raft
turbid condor
#

Like the bot will only assign levels till u told it

cloud dawn
#

Yep.

thin raft
#

!e

import math
lvl=int(math.sqrt(1000000/5+10)-1)
print(lvl)```
unkempt canyonBOT
#

@thin raft :white_check_mark: Your 3.11 eval job has completed with return code 0.

446
cloud dawn
turbid condor
#

!e

lvl=1
xp=15
xp_next=lvl*10

if xp>xp_next:
    lvl += 1
    print('level up')
    print(lvl)
else:
    print('XD')
unkempt canyonBOT
#

@turbid condor :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | level up
002 | 2
turbid condor
#

Welp i use this approach

vale wing
cloud dawn
#

I mean exponential equations are great for xp systems.

vale wing
#

Yeah

#

The more xp you have the more you need to earn to next level

formal basin
#

how could I get a guild id in redis

thin raft
buoyant quail
#
async def my_function_that_gets_id_from_redis():
    # your code

await my_function_that_gets_id_from_redis()

pixels_snek_2

formal basin
formal basin
#

<@&831776746206265384>

slate swan
#

@lavish vortex

formal basin
#

here

slate swan
#

@runic pond

buoyant quail
languid jungle
#

!ban 862434693232197654 That sort of language is not allowed here.

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied ban to @dry dust permanently.

buoyant quail
vale wing
#

Discord bots moment

formal basin
buoyant quail
#

If you don't know what guild do you want, what do you want to get?

formal basin
#

oh.

#

wait nvm I just realised i will get ratelimited

feral frost
#

hello so i have this code

videos = pytube.Search(song_title).results

    if not videos:
        await interaction.response.send_message("No search results found for the given song title.")
        return

    video = videos[0]

    audio_stream = video.streams.filter(only_audio=True).order_by('abr').last()

    audio_file = audio_stream.download()

    if interaction.user.voice is None:
        await interaction.response.send_message("You need to be in a voice channel to use this command.")
        
    await interaction.response.send_message(f"Now playing **{song_title}**")
    
    vc = await interaction.user.voice.channel.connect()

    vc.play(discord.FFmpegPCMAudio(audio_file))
    playback_event.set() 

    await playback_event.wait()```

and i get the error 

```error
await interaction.response.send_message(f"Now playing **{song_title}**")
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction```
feral frost
#

? how

formal basin
#

your interaction

unkempt canyonBOT
#
Our youtube-dl, or equivalents, policy

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
#

We cant help you

formal basin
slate swan
#

πŸ—Ώ

#

Do you know what you are talking about?

feral frost
#

i just use it in my server

slate swan
#

Doesnt matter

buoyant quail
formal basin
feral frost
#

i have youtube premium

slate swan
#

So?

feral frost
#

i pay for youtube

formal basin
feral frost
#

ah damn

#

so no help ?

slate swan
#

Nope

feral frost
#

bruh moment

slate swan
#

Its against YouTube tos

formal basin
slate swan
#

Same

formal basin
#

do they care?

feral frost
#

lara bot uses youtube

#

its a verified bot

formal basin
#

oh ok

feral frost
slate swan
feral frost
buoyant quail
feral frost
#

yes but i have that but youtube is easier

#

and has bigger library

slate swan
#

But you cant use it for a discord bot

feral frost
#

how do i use spotify thing for music ? anyone got some information on a tutorial or anything ?

feral frost
vale wing
#

Create own music service πŸ₯Ά

feral frost
#

that is actually a good idea

#

thanku

pure sparrow
#

hi guys, I just wondered if you knew some servers to advertise our discord bots, because it's actually hard to get people interested about the bot... thanks

buoyant quail
thin raft
night crater
#

Not really

#

They just took over the previous bot before them I

final iron
#

It's difficult to create a popular one now-a-days

slate swan
#

first time making a music bot

#

also first time making a bot with python

#

worth it ngl

sick birch
slate swan
pure sparrow
pure sparrow
little tendon
#
    async def play_music(self):
        print("play_music method called.")
        if len(self.music_queue) > 0:
            print("it is over 0")
            self.is_playing = True
            print("it is true")
            voice_channel = self.music_queue[0][1]
            m_url = self.music_queue[0][0]['source']
            print(m_url)
            self.music_queue.pop(0)

            if self.vc is None or not self.vc.is_connected() or self.vc.channel != voice_channel:
                print("awaiting voice_channel.connect")
                try:
                    self.vc = await voice_channel.connect()
                except Exception as e:
                    print(f"Failed to connect to voice channel: {e}")
            print("URL of song: ", m_url)  # Debug

            try:
                self.vc.play(discord.FFmpegPCMAudio(
                    executable="C:\\Users\\starf\\PycharmProjects\\AudioAnalyser\\venv\\Lib\\site-packages\\imageio_ffmpeg\\binaries\\ffmpeg-win32-v4.2.2.exe",
                    source=m_url))
            except Exception as e:
                print(f"Exception occurred while playing music in play_music method: {str(e)}")

            while self.vc.is_playing():
                await asyncio.sleep(1)

            # If more, play next
            if len(self.music_queue) > 0:
                self.is_playing = False
                await self.play_music()

            # If no more, disconnect
            else:
                self.is_playing = False
                await self.vc.disconnect()

        else:
            print("is not playing")
            self.is_playing = False```

impossible. it stops working at
```py
                try:
                    self.vc = await voice_channel.connect()
                except Exception as e:
                    print(f"Failed to connect to voice channel: {e}")```
its like it has no idea that the bot IS connected to a channel. im going insane on this. any insight?
tepid dagger
#

im trying to print elements out of a list with slash commands but when i print it with a loop it only prints the first element of the list

#
async def view(interaction = discord.Interaction):
  if len(homework) > 0:
    for x in range(len(homework)):
      await interaction.response.send_message(f'{homework[x]}: {homework_notes[x]}')```
#

how do i get it to print all the elements

naive briar
#

You can only use the InteractionResponse.send_message once

#

If you need to send more than one message, use interaction.followup.send instead

#

!d discord.Interaction.followup

unkempt canyonBOT
tepid dagger
#

ok

naive briar
#

!e

a = ["cat", "meow"]

for b in a:
    print(b)
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | cat
002 | meow
tepid dagger
#

oh yea

#

thanks

tepid dagger
#

so do i use that to send everything or just the first message

hasty pike
#

How do i check if on_message has image or video in it?

naive briar
#

!d discord.Message.attachments

unkempt canyonBOT
naive briar
#

Check if this is empty or not

naive briar
tepid dagger
#

so like

naive briar
#

interaction.response.send_message can only be used once, interaction.followup.send can be used multiple times

tepid dagger
#

await interaction.followup.send('stuff')

hasty pike
#

if message.attachments == None:

This way?

naive briar
#

!e

print([] == None)
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.

False
naive briar
#

No

hasty pike
#

Then?

naive briar
#

!e

if []:
    print(0)

if [0]:
    print(1)

unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.

1
blazing girder
#

!e

test = []
test.append("hello")
unkempt canyonBOT
#

@blazing girder :warning: Your 3.11 eval job has completed with return code 0.

[No output]
blazing girder
#

:c

slate swan
#

!e

test = []
test.append("hello")
print(test)
unkempt canyonBOT
#

@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.

['hello']
blazing girder
#

ah lmao

#

totally forgot

slate swan
#

Happens a lot lmao

blazing girder
#

do you know why?

slate swan
#

Can I see the code?

blazing girder
#

one moment

slate swan
#

oh

buoyant quail
#

You are not calling append

#

You are trying to change it

slate swan
#

it's supposed to be user_history.append(zumsagen)

blazing girder
#

ohhh damn

slate swan
#

not user_history.append = (zumsagen)

blazing girder
#

oh shit now i see

#

didnt notice that there ngl
looked normal to me xd

#

thx for the help :3

slate swan
#

❀️

#

<3

#

Why is discord changing ascii emojis to actual emojis tho

#

kinda weird

naive briar
#

Because your settings

slate swan
#

Woah there's settings for this?

naive briar
#

Yes?

cedar jacinth
#

how to make discord.py send avatar image (not sending url but send image)

buoyant quail
#

Or you can just escape it with backslash

buoyant quail
#

:)
πŸ™‚

slate swan
#

Ah shit now I see

#

I didn't know this setting existed danklaugh

#

:)

#

WOAH

blazing girder
#

life changing

slate swan
blazing girder
#

is there a difference
between
test = [] and test = {}
?

slate swan
#

[] is a list and {} is a dictionary

naive briar
unkempt canyonBOT
#

await to_file(*, filename=..., description=None, spoiler=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Converts the asset into a [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") suitable for sending via [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send").

New in version 2.0.
slate swan
#

or a set afaik

cedar jacinth
naive briar
#

!d discord.User.avatar

unkempt canyonBOT
#

property avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Asset "discord.Asset") for the avatar the user has.

If the user has not uploaded a global avatar, `None` is returned. If you want the avatar that a user has displayed, consider [`display_avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.display_avatar "discord.User.display_avatar").
cedar jacinth
#

no, mention and download avatar then send the image (not url)

naive briar
#

What URL?

naive briar
slate swan
#

That's what it is

cedar jacinth
#

thx bro

#

if message.content == '!avatar':
clientProfilePicture = message.author.avatar.to_file
await message.channel.send(clientProfilePicture)

#

good?

naive briar
#

No

#

to_file is a function, that returns a coroutine, which you need to await

#

And it returns a discord.File object, which should be passed into the file or files argument of the send method

cedar jacinth
#

i need the full code i dont understand 😭

naive briar
#

I don't spoonfeed

#

I just explained it the best I can

buoyant quail
slate swan
# unkempt canyon

btw I didn't know that
I've always done something like

response = requests.get(user.avatar.url)
                        
filepath = avatar_hash + '.png'
with open(filepath, 'wb') as f:
    f.write(response.content)

await message.channel.send(file=discord.File(filepath))
naive briar
#

requests πŸ˜“

buoyant quail
#

Saving file locally :p

slate swan
#

lmaoooooooooo

buoyant quail
#

Here it's better to use methods from dpy, but fyi there is

#

!d io.BytesIO (same as file but in memory)

unkempt canyonBOT
#

class io.BytesIO(initial_bytes=b'')```
A binary stream using an in-memory bytes buffer. It inherits [`BufferedIOBase`](https://docs.python.org/3/library/io.html#io.BufferedIOBase "io.BufferedIOBase"). The buffer is discarded when the [`close()`](https://docs.python.org/3/library/io.html#io.IOBase.close "io.IOBase.close") method is called.

The optional argument *initial\_bytes* is a [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object) that contains initial data.

[`BytesIO`](https://docs.python.org/3/library/io.html#io.BytesIO "io.BytesIO") provides or overrides these methods in addition to those from [`BufferedIOBase`](https://docs.python.org/3/library/io.html#io.BufferedIOBase "io.BufferedIOBase") and [`IOBase`](https://docs.python.org/3/library/io.html#io.IOBase "io.IOBase"):
slate swan
#

So, I could've just done discord.File(io.BytesIO(response.content))?

buoyant quail
#

Actually i guess discord.File can take bytes too
But yeah

#

!d discord.File

unkempt canyonBOT
#

class discord.File(fp, filename=None, *, spoiler=..., description=None)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for sending file objects.

Note

File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
buoyant quail
#

ok it can't

slate swan
#

And then there's await messagable.send(file=user.avatar.to_file())

#

Jeez

naive briar
#

to_file() need to to awaited

slate swan
#

Oh I see

#

Should it go like await messagable.send(file=await user.avatar.to_file())?

#

Python is like "There's always a better alternative, only if you know."

tepid dagger
#

can you take dates as an input

#

docs say no so im guessing not

buoyant quail
#

You always can convert it by yourself

tepid dagger
#

E

#

does anyone have code i can steal i am lazy

buoyant quail
#

by yourself :)

tepid dagger
#

true

buoyant quail
tepid dagger
#

i can use chatgpt ig πŸ’€

slate swan
tepid dagger
#

do you know how to do it without converting it yourself

slate swan
#

There's stuff like datetime.strptime or you can make a commands.Converter and parse it yourself I guess

buoyant quail
#

Instead of searching for ready one you could already write it
It is just two lines of code

tepid dagger
#

ok

buoyant quail
#

!d datetime.datetime.strptime

unkempt canyonBOT
#

classmethod datetime.strptime(date_string, format)```
Return a [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") corresponding to *date\_string*, parsed according to *format*.

If *format* does not contain microseconds or timezone information, this is equivalent to:

```py
datetime(*(time.strptime(date_string, format)[0:6]))
```  [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "ValueError") is raised if the date\_string and format can’t be parsed by [`time.strptime()`](https://docs.python.org/3/library/time.html#time.strptime "time.strptime") or if it returns a value which isn’t a time tuple. See also [strftime() and strptime() Behavior](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior) and [`datetime.fromisoformat()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat "datetime.datetime.fromisoformat").
tepid dagger
#

k ty ive never used datetime lol

little tendon
#

okay... this is getting so annoying. anyone know why this doesnt work?

async def join(ctx):
    if (ctx.author.voice):
        channel = ctx.message.author.voice.channel
        print("Attempting to join voice channel...")
        await channel.connect()
        print("Joined voice channel successfully!")
    else:
        await ctx.send()```

```lsd2#0 .join 1133330391730765854
Attempting to join voice channel...```

this is my console output. makes no sense, all it is supposed to do is join a channel.

But it shows as there...
little tendon
slate swan
#

oh thats odd since the pass_context argument doesnt exist for like 2 years its outdated

little tendon
#

i saw it on a tutorial since ive been trying to get my bot to join for like 5 hours

#

ive tried so many things. do you know the problem? ive given my bot admin, every permission, a custom role with only speak enabled.

#

cannot for the life of me get it to work

slate swan
#

youtube tutorial explains it all

#

☠️

little tendon
#

Which tutorial

#

Shouldnt this code work regardless

#

ive done many different attempts

#

all of them stop at await join.

#

Yeah found this tutorial.
same exact code basically

slate swan
#

using a youtube tutorial is the worst idea to make a discord bot

little tendon
#

Then tell me what to use

#

ive gone to github to find some code

#

all the same, ctx.message.author.voice.channel.join

#

gone on forums all the same

#

thats why im asking for help.

slate swan
slate swan
little tendon
#

connect i mean

#

told you ive been up all night im tired and just need a staight answer

slate swan
#

!d discord.VoiceChannel.connect

unkempt canyonBOT
#

await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>, self_deaf=False, self_mute=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Connects to voice and creates a [`VoiceClient`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceClient "discord.VoiceClient") to establish your connection to the voice server.

This requires [`voice_states`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.voice_states "discord.Intents.voice_states").
slate swan
#

This requires voice_states. did you enable this intent?

little tendon
#

No

#

nowhere said any of that.

#

How

slate swan
#

how you define intents now?

little tendon
#

intents = discord.Intents.default()

all i have is that. idk how id write voice_states

#

discord.voice_states

slate swan
#

the .default one does have this intent

little tendon
#

Then i have no idea what the problem is. its weird because my bot does join the chat

slate swan
#

you have any error handler?

little tendon
#

i am not leet coder. I only have an if and else. but i know that it is awaiting forever since it is not allowed to join

#

someone told me captcha is blocking it. idk how true it is

#

and i dont believe it since there isnt even any audio being played

slate swan
#

the reason you dont get the other print in the console is mostlikely that the connect method errors but you have error handler silencing it

little tendon
#

other errors get shown. im not sure why not this one

slate swan
#

did you try debugging it?

little tendon
#

there is one line needing a debug in that example code but yes

slate swan
#

what do you understand as debug

little tendon
#

print line

slate swan
#

and what did you try

little tendon
#

i know there is some magic you can do in debug mode but i dont know how to use it.

#

i showed you.

@client.command()
async def join(ctx):
    if (ctx.author.voice):
        channel = ctx.message.author.voice.channel
        print("Attempting to join voice channel...")
        await channel.connect()
        print("Joined voice channel successfully!")
    else:
        await ctx.send("broken")```
```lsd2#0 .join 1133330391730765854
Attempting to join voice channel...```
slate swan
#

by debugging i mean print out varriables what do they store

little tendon
#

so you wish for me to print the channel

slate swan
#

for example what channel is

little tendon
#
lsd2#0 .join 1133330391730765854
General
Attempting to join voice channel...```
#

i see now that it is not an id

#

maybe that has something to do with it

slate swan
#

what you print out

little tendon
#

it printed out General and Attempting to join voice channel...

slate swan
#

i see what it printed im asking what you are printing out

#

just channel?

little tendon
#

thats all i need to print out right

#

author is obviously me

slate swan
#

how about channel.id

vocal snow
#

Have you set up logging

little tendon
#

lsd2#0 .join 1133330391730765854
1133323696698818593
Attempting to join voice channel...

slate swan
little tendon
#

Yes

#

Its there right now but it doesnt say that it ever accomplishes its task of joining

slate swan
#

is the Rust something the bot?

little tendon
#

Yes

vocal snow
#

Maybe because you're trying to connect to a VC you're already connected to?

little tendon
slate swan
vocal snow
#

Yes, referring to the bot

#

Have you disconnected it before using the command?

little tendon
#

but it never gets past it

slate swan
little tendon
#
async def join(ctx):
    if (ctx.author.voice):
        channel = ctx.message.author.voice.channel
        print(channel.id)
        print("Attempting to join voice channel...")
        await channel.connect()
        print("Joined voice channel successfully!")
    else:
        await ctx.send("broken")```

print("Joined voice channel successfully!")
#

it never gets to that point. thats the huge issue i am facing

naive briar
slate swan
#

cause you are already connected

little tendon
slate swan
#

add a case where its already connected to the voice

vocal snow
#

I am invisible it seems

little tendon
little tendon
#

it may look like its there, but the bot has no capability of utilizing the audio channels

little tendon
slate swan
#

should be some errors but doesnt throw any

#

or you silence them

#

are you able to show some code?

little tendon
#

Sure

intents = discord.Intents.default()

client = commands.Bot(command_prefix=".", intents=intents, help_command=None)

@client.event
async def on_message(message):
    print(message.author, message.content, message.channel.id)
    await client.process_commands(message)


@client.event
async def on_ready():
    print(f'We have logged in as {client.user}')


@client.command()
@has_permissions(administrator=True)
async def clean(ctx, llimit: int):
    await ctx.channel.purge(limit=llimit)
    await ctx.send('Cleared by <@{.author.id}>'.format(ctx))


@clean.error
async def clear_error(ctx, error):
    if isinstance(error, commands.errors.MissingPermissions):
        await ctx.send("You cant do that!")

@client.command()
async def join(ctx):
    if (ctx.author.voice):
        channel = ctx.message.author.voice.channel
        print(channel.id)
        print("Attempting to join voice channel...")
        await channel.connect()
        print("Joined voice channel successfully!")
    else:
        await ctx.send("broken")

client.run(TOKEN)```
little tendon
#

thats most of it. the rest is just other classes

slate swan
little tendon
# upbeat ice https://discordpy.readthedocs.io/en/stable/logging.html#logging-setup

did this and

client.run(TOKEN, log_handler=handler)

  File "C:\Users\starf\PycharmProjects\AudioAnalyser\RustSolutions.py", line 390, in <module>
    client.run(TOKEN, log_handler=handler)
  File "C:\Users\starf\PycharmProjects\AudioAnalyser\venv\lib\site-packages\discord\client.py", line 723, in run
    return future.result()
  File "C:\Users\starf\PycharmProjects\AudioAnalyser\venv\lib\site-packages\discord\client.py", line 702, in runner
    await self.start(*args, **kwargs)
  File "C:\Users\starf\PycharmProjects\AudioAnalyser\venv\lib\site-packages\discord\client.py", line 663, in start
    raise TypeError("unexpected keyword argument(s) %s" % list(kwargs.keys()))
TypeError: unexpected keyword argument(s) ['log_handler']```
slate swan
naive briar
#

!d discord.Client.run

unkempt canyonBOT
#

run(token, *, reconnect=True, log_handler=..., log_formatter=..., log_level=..., root_logger=False)```
A blocking call that abstracts away the event loop initialisation from you.

If you want more control over the event loop then this function should not be used. Use [`start()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.start "discord.Client.start") coroutine or [`connect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.connect "discord.Client.connect") + [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login "discord.Client.login").

This function also sets up the logging library to make it easier for beginners to know what is going on with the library. For more advanced users, this can be disabled by passing `None` to the `log_handler` parameter.

Warning

This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns.
little tendon
#

newest i think. updated today

naive briar
#

Or, it's not discord.py

slate swan
little tendon
#

import discord?

slate swan
little tendon
#

wtf

#

🀯

slate swan
#

how about you do pip show discord.py in console

little tendon
#
Name: discord.py
Version: 1.7.3
Summary: A Python wrapper for the Discord API
Home-page: https://github.com/Rapptz/discord.py
Author: Rapptz
Author-email:
License: MIT
Location: c:\users\starf\appdata\local\programs\python\python38-32\lib\site-packages
Requires: aiohttp
Required-by:

C:\Users\starf>```
slate swan
#

version 1.7.3

upbeat ice
#

:0

slate swan
#

yeah def newest

#

pip install -U discord.py to update

little tendon
#

xd. newest discord then xddd

#

lol lets see what happens now.....

#
  File "C:\Users\starf\PycharmProjects\AudioAnalyser\RustSolutions.py", line 390, in <module>
    client.run(TOKEN, log_handler=handler)
  File "C:\Users\starf\PycharmProjects\AudioAnalyser\venv\lib\site-packages\discord\client.py", line 723, in run
    return future.result()
  File "C:\Users\starf\PycharmProjects\AudioAnalyser\venv\lib\site-packages\discord\client.py", line 702, in runner
    await self.start(*args, **kwargs)
  File "C:\Users\starf\PycharmProjects\AudioAnalyser\venv\lib\site-packages\discord\client.py", line 663, in start
    raise TypeError("unexpected keyword argument(s) %s" % list(kwargs.keys()))
TypeError: unexpected keyword argument(s) ['log_handler']

Process finished with exit code 1
``` this still happens.
naive briar
#

They probably have multiple Discord libraries

vocal snow
#

inb4 pycharm venv confusion

upbeat ice
slate swan
little tendon
slate swan
#

run this code

slate swan
little tendon
#

i did

slate swan
little tendon
#

i ran

slate swan
#

and how about you try to run code now?

little tendon
#

Traceback (most recent call last):
File "C:\Users\starf\PycharmProjects\AudioAnalyser\RustSolutions.py", line 390, in <module>
client.run(TOKEN, log_handler=handler)
File "C:\Users\starf\PycharmProjects\AudioAnalyser\venv\lib\site-packages\discord\client.py", line 723, in run
return future.result()
File "C:\Users\starf\PycharmProjects\AudioAnalyser\venv\lib\site-packages\discord\client.py", line 702, in runner
await self.start(*args, **kwargs)
File "C:\Users\starf\PycharmProjects\AudioAnalyser\venv\lib\site-packages\discord\client.py", line 663, in start
raise TypeError("unexpected keyword argument(s) %s" % list(kwargs.keys()))
TypeError: unexpected keyword argument(s) ['log_handler']

Process finished with exit code 1
😒

slate swan
#

you ran pip install -U discord.py?

little tendon
#

earlier yes, when u sent it

turbid condor
#
import os
import sys

py_exec = sys.executable
uninstall_list = " -m pip uninstall nextcord py-cord interactions.py disnake dislash discord-py-slash-command discord.py-message-components enhanced-discord.py novus hata discord-interactions discord.py-self discord.py-self.embed discord2 python-discord reactionmenu discord_py_buttons discord_slash discord.py discord discord-ext-forms discord-ext-alternatives"

os.system(py_exec + uninstall_list)
os.system(py_exec + " -m pip install discord.py --no-cache-dir")
vocal snow
#

Are you doing this in the pycharm terminal

slate swan
#

at the top of your script print this print(discord.__version__)

turbid condor
#

This one?

little tendon
slate swan
little tendon
turbid condor
#

Oh i didn't see

slate swan
little tendon
#

in same evnv

slate swan
vocal snow
#

When you ran pip show discord.py it didn't show a venv location so

little tendon
#

Location: c:\users\starf\appdata\local\programs\python\python38-32\lib\site-packages
shows this

vocal snow
#

Can you check the pycharm packages tab

upbeat ice
#

if you are using pycharm go ctrl+alt+s

#

go to python interpreter

little tendon
upbeat ice
slate swan
#

search for discord.py

little tendon
slate swan
#

uninstall discord

vocal snow
#

Does pycharm terminal not automatically activate the venv

little tendon
#

Yall telling me magical spells.

little tendon
#

i uninstalled discord

slate swan
#

and does it work now?

little tendon
#

lmfao i sent .join and now it shows this.

C:\Users\starf\PycharmProjects\AudioAnalyser\RustSolutions.py:387: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited
  client.add_cog(help_cog(client))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
C:\Users\starf\PycharmProjects\AudioAnalyser\RustSolutions.py:388: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited
  client.add_cog(music_cog(client))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
We have logged in as Rust Solutions#8637
lsd2  1133330391730765854```
vocal snow
#

progress

naive briar
#

At least now it's actually discord.py

slate swan
#

.add_cog must be awaited πŸ˜΅β€πŸ’«

little tendon
#

Yes i have some external classes

#

ill comment them out for nwo

little tendon
#

i can always add the cogs into the main class later

#

We have logged in as Rust Solutions#8637
lsd2 1133330391730765854
lsd2 1133330391730765854
lsd2 1133330391730765854

brain is gonna explode

#

ctx isnt getting passed?

naive briar
#

!d discord.Intents.message_content

unkempt canyonBOT
#

Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:

β€’ The message was sent by the client

β€’ The message was sent in direct messages

β€’ The message mentions the client

This applies to the following events...

naive briar
#

The bot needs this intent to process commands

little tendon
#
intents = discord.Intents.default()
intents.message_content = True```
#

We have logged in as Rust Solutions#8637
lsd2 .join 1133330391730765854
1133323696698818593
Attempting to join voice channel...
Joined voice channel successfully!

#

YOOOO

#

Xd... well thats awesome. but there is ONE more thing i cannot get working.

it is this monster.

@client.command(pass_context=True, name="playtest", help="Plays a local audio file")
async def playtest(ctx, filename: str):
    print(f"Attempting to play file: {filename}")

    try:
        voice_channel = ctx.message.author.voice.channel
        print(f"Found user's voice channel: {voice_channel}")
    except AttributeError:
        print("User not in a voice channel.")
        return await ctx.send(
            "No channel to join. Make sure you are in a voice channel.")

    permissions = voice_channel.permissions_for(ctx.me)
    if not permissions.connect or not permissions.speak:
        print("No permission to connect or speak.")
        return await ctx.send("I don't have permission to join or speak in that voice channel.")

    voice_client = ctx.guild.voice_client
    if not voice_client:
        print("Bot not connected to a voice channel, attempting to connect.")
        await voice_channel.connect()
        voice_client = discord.utils.get(client.voice_clients, guild=ctx.guild)
        print(f"Connected to voice channel: {voice_channel}")
    else:
        print("Bot already connected to a voice channel.")

    await asyncio.sleep(1)

    try:
        print("Trying to play audio.")
        voice_client.play(
            discord.FFmpegPCMAudio(source=filename, **FFMPEG_OPTIONS, executable="ffmpeg"))  # playing the audio
        print("Audio playing.")
    except Exception as e:
        print(f"Failed to play audio. Error: {e}")

    await ctx.send(f'**Now playing:** {filename}')
    print(f"Sent now playing message: {filename}")```
#
Attempting to play file: playtest.webm
Found user's voice channel: General
Bot not connected to a voice channel, attempting to connect.
Connected to voice channel: General
Trying to play audio.
Audio playing.
Option reconnect not found.
Rust Solutions#8637 **Now playing:** playtest.webm 1133330391730765854
Sent now playing message: playtest.webm
#

but i never would have figured out the discord.py thing since i thought they were the same thing.

#

OH MY GOOOOOODSSS

#

I GOT IT BOYS AND GIRLS AND EVERYONE

slate swan
#

πŸ‘

little tendon
#
voice_client = ctx.guild.voice_client
    if not voice_client:
        print("Bot not connected to a voice channel, attempting to connect.")
        vc = await voice_channel.connect()
        voice_client = discord.utils.get(client.voice_clients, guild=ctx.guild)
        print(f"Connected to voice channel: {voice_channel}")```
#

😎

hasty pike
polar hornet
#

Hey guys I made a discord bot on pycharm but whenever I close pycharm the bot goes offline. How do I make it so the bot is up at all times even if my pycharm is closed?

upbeat ice
old geyser
#

Where can I find a discord bot coder ?? Because I need to hire one!

turbid condor
#

Try searching up a freelance site

#

And

#

!rule 9

unkempt canyonBOT
#

9. Do not offer or ask for paid work of any kind.

cloud dawn
#

Just don't buy anything under 50 bucks lol

gilded depot
#
@client.event
async def on_message(message):
    if message.author.bot:
      print("Nevermind guys!")
      return

    bucket = cd_mapping.get_bucket(message)
    retry_after = bucket.update_rate_limit()

    if retry_after:
        channel = message.channel

        permissions_to_remove = discord.PermissionOverwrite(send_messages=False)
        permissions_to_restore = channel.overwrites_for(message.author)

        await channel.set_permissions(message.author, overwrite=permissions_to_remove)
        await message.channel.send(
            f"{message.author.mention}, that is way too fast. You are disabled from speaking here for 1 minute."
        )

        await asyncio.sleep(60)  # Use asyncio.sleep instead of time.sleep in async functions

        await channel.set_permissions(message.author, overwrite=permissions_to_restore)

    else:
        await client.process_commands(message)

This is my code for a cooldown. When I run it and go over 20 messages per miutes, Irt does ssay "That isway too fast" But it doesnt disable users permissions. Whats going on help.

grim robin
#

Hello. I have a bot that has its commands synced fine upon logging in to Discord. Everything works fine and commands respond properly. Upon joining a new server though, all commands are stuck in a "thinking" state and bot never replies. If I reconnect the bot, they seem to sync fine to that new server and work again

warm coral
#

a dumb question

can i code a bot on the idle shell?

upbeat ice
grim robin
#

yes

upbeat ice
#

can you show your code

grim robin
#
@client.event
async def on_ready():
    await client.tree.sync()

@client.event
async def on_guild_join(guild):
    await client.tree.sync(guild=guild)
upbeat ice
#

also you shouldn't sync when logging in. It's unnecessary - you only need to sync when your commands change

#

you also dont need to sync every time the bot joins a guild

#

the commands are globally synced with discord

#

Make a sync command that only you can call and use it whenever you want to update your commands

warm coral
#

can someone tell me the importance of Async and await?

#

and how to use them

#

and for what?

upbeat ice
warm coral
#

ty

unkempt canyonBOT
#
Concurrency in Python

Python provides the ability to run multiple tasks and coroutines simultaneously with the use of the asyncio library, which is included in the Python standard library.

This works by running these coroutines in an event loop, where the context of the running coroutine switches periodically to allow all other coroutines to run, thus giving the appearance of running at the same time. This is different to using threads or processes in that all code runs in the main process and thread, although it is possible to run coroutines in other threads.

To call an async function we can either await it, or run it in an event loop which we get from asyncio.

To create a coroutine that can be used with asyncio we need to define a function using the async keyword:

async def main():
    await something_awaitable()

Which means we can call await something_awaitable() directly from within the function. If this were a non-async function, it would raise the exception SyntaxError: 'await' outside async function

To run the top level async function from outside the event loop we need to use asyncio.run(), like this:

import asyncio

async def main():
    await something_awaitable()

asyncio.run(main())

Note that in the asyncio.run(), where we appear to be calling main(), this does not execute the code in main. Rather, it creates and returns a new coroutine object (i.e main() is not main()) which is then handled and run by the event loop via asyncio.run().

To learn more about asyncio and its use, see the asyncio documentation.

upbeat ice
#

check out the guides

grim robin
#

removing this code didn't change the behavior on newly joined servers. Commands still don't work there

upbeat ice
#

did you make a sync command ?

#
    async def sync(self, ctx: commands.Context, guilds: commands.Greedy[discord.Object],
                   spec: Optional[Literal["~", "*", "^"]] = None) -> None:
        if not guilds:
            if spec == "~":
                synced = await ctx.bot.tree.sync(guild=ctx.guild)
            elif spec == "*":
                ctx.bot.tree.copy_global_to(guild=ctx.guild)
                synced = await ctx.bot.tree.sync(guild=ctx.guild)
            elif spec == "^":
                ctx.bot.tree.clear_commands(guild=ctx.guild)
                await ctx.bot.tree.sync(guild=ctx.guild)
                synced = []
            else:
                synced = await ctx.bot.tree.sync()

            await ctx.send(
                f"Synced {len(synced)} commands {'globally' if spec is None else 'to the current guild.'}"
            )
            return

        ret = 0
        for guild in guilds:
            try:
                await ctx.bot.tree.sync(guild=guild)
            except discord.HTTPException:
                pass
            else:
                ret += 1

        await ctx.send(f"Synced the tree to {ret}/{len(guilds)}.")``` @grim robin
grim robin
#

still nothing. If I disc/reconnect the bot they all work fine

upbeat ice
#

did you run the command?

grim robin
#

yes

#

I removed the previous sync lines in my code and added your command

#

run it in a newly joined server

upbeat ice
#

can I see how you ran it

#

you should only have to do (your prefix)sync in your main guild. It will sync globablly to all servers

#

you dont need to run it again unless you change a command or add new ones

gilded depot
#

@upbeat ice

#

@grim robin

#
@client.event
async def on_message(message):
    if message.author.bot:
      print("Nevermind guys!")
      return

    bucket = cd_mapping.get_bucket(message)
    retry_after = bucket.update_rate_limit()

    if retry_after:
        channel = message.channel

        permissions_to_remove = discord.PermissionOverwrite(send_messages=False)
        permissions_to_restore = channel.overwrites_for(message.author)

        await channel.set_permissions(message.author, overwrite=permissions_to_remove)
        await message.channel.send(
            f"{message.author.mention}, that is way too fast. You are disabled from speaking here for 1 minute."
        )

        await asyncio.sleep(60)  # Use asyncio.sleep instead of time.sleep in async functions

        await channel.set_permissions(message.author, overwrite=permissions_to_restore)

    else:
        await client.process_commands(message)

This is my code for a cooldown. When I run it and go over 20 messages per miutes, Irt does ssay "That isway too fast" But it doesnt disable users permissions. Whats going on help.

upbeat ice
#

does the user have elevated permissions that still give them access?

gilded depot
#

what does that mean

#

itn doesnt disable it for a minute like the coee ssy

#

code says*

upbeat ice
#

what permissions does the user you are trying to disable permissions for have?

upbeat ice
#

add this before you sleep

gilded depot
#

f

#

sorry wrong chat

gloomy hound
#

Hey, I have this slash command that should show a View with some buttons

class ModrouletteView(discord.ui.View):
    def __init__(self):
        super().__init__()
        print("here")
        @discord.ui.button(style=discord.ButtonStyle.primary, label="no")
        async def participate(self, interaction: discord.Interaction, button: discord.ui.Button):
            pass
        
        @discord.ui.button(style=discord.ButtonStyle.red, label="yes !", emoji="🀞")
        async def roll(self, interaction: discord.Interaction, button: discord.ui.Button):
            pass
@self.slash_command(name="hi", description="yes")
async def modroulette(interaction: discord.ApplicationContext):
        await interaction.respond(embed=MyEmbed(), view=MyView())

The here is printed but for some reasons it doesn't show the view

slate swan
#

is the self.slash_command(name="hi", description="yes") supposed to be a decorator?

gloomy hound
slate swan
#

is that inside a cog?

gloomy hound
#

A discord.Bot

slate swan
#

what library is that

gloomy hound
#

PyCord

slate swan
#

pretty sure thats not how to register a slash command in it inside a class

gloomy hound
#

everything works

slate swan
#

also if this method is inside a class it must have self param

gloomy hound
#

except that

#

like the embed is shown

#

but no view

slate swan
#

can you show more code?

gloomy hound
#

nah too big

#

And that would not be useful

slate swan
#

cause with this it looks like shouldnt work maybe im not getting osmethjing

slate swan
unkempt canyonBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

gloomy hound
#

yea true

#

But I don't wanna send all my code πŸ˜“

#

Basically this is shown

#

But not the button

slate swan
#

class ModrouletteView(discord.ui.View): you create other view view=MyView()

gloomy hound
#

cuz I added the same script but edited the names

#

don't worry it's litterally same but with other names

slate swan
#

well with more context of code where its located and how its defined i cant tell anthing more

slate swan
#

well if you know better than me

gloomy hound
#

that's not what I mean

#

Just the code is basically a bot and as you saw it works except the view

slate swan
#

but i dont really care what commands you have and what it does i just wanna see the context of this code snippet you provided where its located and how its defined

gloomy hound
#

well ok

#

there are useless variables cuz I removed commands that contain sensitive info

#

as api key

slate swan
#

thats interesting that this command works ```py
@self.slash_command(name="modroulette", description="Get someone kicked out of the server >:D")
async def modroulette(interaction: discord.ApplicationContext):
await interaction.respond(embed=ModrouletteEmbed(interaction), view=ModrouletteView())

gloomy hound
#

me neither

#

but that was the only way to get self

slate swan
#

why cant you define it outside class? when creating bot instance

gloomy hound
#

And my main.py should not contain any discord stuff

naive briar
# gloomy hound But not the button
class ModrouletteView(discord.ui.View):
    def __init__(self):
        super().__init__()
        print("here")
        @discord.ui.button(style=discord.ButtonStyle.primary, label="Participate")
        async def participate(self, interaction: discord.Interaction, button: discord.ui.Button):
            pass
        
        @discord.ui.button(style=discord.ButtonStyle.red, label="Roll !", emoji="🀞")
        async def roll(self, interaction: discord.Interaction, button: discord.ui.Button):
            pass

Can you see what's wrong?

gloomy hound
#

no..

slate swan
#

oh yeah the components are declared inside __init__

gloomy hound
#

that's basically why I ask

naive briar
#

The buttons are being defined in the class' __init__

gloomy hound
#

OH

naive briar
#

Just move them down an indent

gloomy hound
#

TY

#

ty too for answering down

slate swan
gilded depot
#

@upbeat ice

#

I ran it

#

and it printed:

<Permissions value=140737488355327>
#

@Bransdon

#

@upbeat ice

upbeat ice
gilded depot
#

yes

upbeat ice
#

What permissions do you have in the guild

gilded depot
#

do I check this on the developer portal.

upbeat ice
#

You can check in the server settings. Is it your server?

gilded depot
#

ye

#

yes*

upbeat ice
#

Then that's why you can still access the channel

gilded depot
#

ok

upbeat ice
#

Your perms > send messages

gilded depot
#

i have several alt account tjough

upbeat ice
#

Try on an alt account with basically only the permission to send messages

gilded depot
#

ok

cloud dawn
#

Doesn't Discord have the show as role thingy

upbeat ice
#

Yeah it does

odd minnow
#

@upbeat ice this is @gilded depot 's alt account

upbeat ice
#

Ok

odd minnow
#

just testing now

#

@upbeat ice you are actually a lifesaveer

#

it workedon this alt ccount

#

thx so much

upbeat ice
#

πŸ‘

gilded depot
#

@upbeat ice I have another query

vital heath
#

What is the best way to convert commands with traditonal prefixes into slash commands. right now all my commands are using client.command

upbeat ice
upbeat ice
slate swan
vital heath
slate swan
#

that like i said hybrid registers two commands one is with prefix and one is slahs

#

while when you register app_command its only slash

vital heath
#

sounds good

#

thanks

reef sonnet
#

Hello, ive been searching all day trying to find a way to make a list to show every role like dyno, but i couldnt find anything so whats a way to do it?

slate swan
#

you need to typehint the argument as discord.Role

reef sonnet
#

alright ill try that

#

It works thanks joe_salute

slate swan
#

πŸ‘

gilded depot
#

@upbeat ice the one about the warn command

slate swan
#

i need help, ive tried several times to add buttons, onto embeds, but it never works for me, when i run the command, it gives errors, not the editor, someone please help me further upon this (im wanting the buttons for a bot invite link)

#

Show the errors maybe

agile latch
#

Hey im trying to get into coding my own discord bot, any tips as to how i should get familiar with the discord library?

slate swan
#

There are a lot of examples in the discord.py github

#

Reading these would be helpful

fresh smelt
#

so basically i have a discord bot
and i make it online everyday thru my terminal

and in this terminal i added options like for example info and exit

and whenever you type those it works perfectly

but the only problem is the bot is just online and doesnt respond to the commands anymore
if someone could help me further more i will send the code in dms

please help :D

#

@frigid estuary

frigid estuary
#

Hm.... did you give it the intents

lofty lance
#

can anyone share the link of drag down funtion in discord.py docs

turbid condor
lofty lance
naive briar
#

!d discord.ui.Select

unkempt canyonBOT
#

class discord.ui.Select(*, custom_id=..., placeholder=None, min_values=1, max_values=1, options=..., disabled=False, row=None)```
Represents a UI select menu with a list of custom options. This is represented to the user as a dropdown menu.

New in version 2.0.
unique lichen
#

how to stop this log spam

buoyant quail
#

Show your tasks and how are you running them

slate swan
#

Easiest way would be to disable warnings skull 🀝

buoyant quail
#

xd

unique lichen
vale wing
unique lichen
buoyant quail
vale wing
#

If you actually add that "timezone" to first time you will get close value to second one

unique lichen
#

can someone also help out with like how to attach a local file in attachments ? i am using paginator so cant use normal .send(file =f ) method

buoyant quail
agile latch
#

Hey so I'm trying to get my bot to respond to specific content in people's messages, basically like a moderating tool

#

Internet research and chatgpt lead me to this

#

So it technically works and responds to a message when it contains "IP", but it also recognizes it if it's within a word, meaning it responds, for example, to the word "nipple"

#

Furthermore I get an error message in the terminal

formal basin
#

I get these errors even though nothing is happening

formal basin
#

oh

#

bro

#

you defined your bot as client

#

so why are you using bot?

unique lichen
agile latch
#

idk it kept showing errors with "bot" so I just switched it to "client" πŸ’€

#

how would I go about defining "bot"

formal basin
#

...

agile latch
#

hey man if I had this shit figured out I wouldn't be on here πŸ˜‚

formal basin
#

not bot.process_commands(message)

agile latch
formal basin
#

you need await it

buoyant quail
#

He is using an actual client it looks

agile latch
#

what does that even mean

formal basin
buoyant quail
#

Client and Bot are different classes. Client has no built-in prefix commands.

agile latch
#

its my first time trying this type of stuff 😭

agile latch
buoyant quail
#

You need to define it ofc

agile latch
#

yea so how would I define it

formal basin
buoyant quail
formal basin
#

then remove the process commands

agile latch
#

like this ?

formal basin
#

yes

agile latch
#

kk i'll restart the bot and tell u

#

so I'm guessing I need to define client

#

or whatever

formal basin
formal basin
agile latch
formal basin
#

scroll down a bit

agile latch
#

the code is 165 lines long

#

define a bit

formal basin
#

show me line 9 to line 16

agile latch
formal basin
#

yes

#

ok

vestal yew
#

I want to link the commands file located in the 'commands' folder within my 'discord' folder to my bot file. How can I do that?

agile latch
#

intents = discord.Intents.default() intents.message_content = True bot = commands.Bot(command_prefix='>', intents=intents)

#

do I just slap this in it

formal basin
#

client=commands.Bot(command_prefix='your-prefix', intents=Intents.all())

#

delete the intents varible

buoyant quail
#

Or do everything by your own

#

!d discord.ext.commands.Bot.add_command

unkempt canyonBOT
#

add_command(command, /)```
Adds a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") into the internal list of commands.

This is usually not called, instead the [`command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin.command "discord.ext.commands.GroupMixin.command") or [`group()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin.group "discord.ext.commands.GroupMixin.group") shortcut decorators are used instead.

Changed in version 1.4: Raise [`CommandRegistrationError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandRegistrationError "discord.ext.commands.CommandRegistrationError") instead of generic [`ClientException`](https://discordpy.readthedocs.io/en/latest/api.html#discord.ClientException "discord.ClientException")

Changed in version 2.0: `command` parameter is now positional-only.
formal basin
# agile latch

under the import logging put from discord.ext import commands

vestal yew
#

client.add_cog(name(client))

Is it like this?

agile latch
formal basin
# agile latch

under from discord.ext import commands put from discord import Intents

formal basin
#

intents = discord.Intents.all()

agile latch
agile latch
formal basin
vestal yew
#

which one is better discord or nextcord

formal basin
agile latch
#

o

formal basin
#

it even says what you need to do

agile latch
#

it does

vestal yew
#

zagzag

vestal yew
formal basin
#

"Did you mean: 'Intents"

formal basin
agile latch
formal basin
# agile latch

delete that code the client = discord.Client(intents=Intents)

agile latch
formal basin
#

yes

agile latch
formal basin
# agile latch

replace app_commands.CommandTree(client) with client.tree