#discord-bots

1 messages · Page 833 of 1

fresh orchid
#
class DroppDownMenu(discord.ui.View):
    @discord.ui.select(placeholder="Choose one option", min_values=1, max_values=1, options=[
        discord.SelectOption(label="CPU", description="The CPUs scores list"),
        discord.SelectOption(label="GPU", description="The GPUs scores list"),
        discord.SelectOption(label="RAM", description="The RAMs scores list"),
        discord.SelectOption(label="All", description="All scores lists")
    ])
    async def callback(self, select, interaction : discord.Interaction):
        if select.values[0] == "CPU":
            await interaction.response.send_message("https://media.discordapp.net/attachments/838857610358292532/931919636461654046/CPU-Scores_Super_Dark_Mode_3.jpg")
        if select.values[0] == "GPU":
            await interaction.response.send_message("https://media.discordapp.net/attachments/838857610358292532/931919674134904982/GPU_Scores_Super_Dark_Mode_5.jpg")
        if select.values[0] == "RAM":
            await interaction.response.send_message("https://media.discordapp.net/attachments/838857610358292532/931919651070423100/RAM_scores_Super_Dark_Mode_4.jpg")
        if select.values[0] == "All":
            await interaction.response.send_message("https://media.discordapp.net/attachments/838857610358292532/931919636461654046/CPU-Scores_Super_Dark_Mode_3.jpg")        
            await interaction.followup.send("https://media.discordapp.net/attachments/838857610358292532/931919674134904982/GPU_Scores_Super_Dark_Mode_5.jpg")
            await interaction.followup.send("https://media.discordapp.net/attachments/838857610358292532/931919651070423100/RAM_scores_Super_Dark_Mode_4.jpg")

How can I add this to a slash command. So in the slash command there is this select menu

fluid spindle
#

You can also convert it to binary data with Bytes.io & then convert it back to an image if you don't want to store an image file.

maiden fable
#

👀

fluid spindle
#

I didn't think of that. I'll go try it

slate swan
#

No I wont

fresh orchid
maiden fable
#

U just make a simple slash command and send that view with interaction.response.send_message("Whatever", view=DroppdownMenu(...))

echo wasp
#

!d discord.Webhook

unkempt canyonBOT
#

class discord.Webhook```
Represents an asynchronous Discord webhook.

Webhooks are a form to send messages to channels in Discord without a bot user or authentication.

There are two main ways to use Webhooks. The first is through the ones received by the library such as [`Guild.webhooks()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.webhooks "discord.Guild.webhooks") and [`TextChannel.webhooks()`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel.webhooks "discord.TextChannel.webhooks"). The ones received by the library will automatically be bound using the library’s internal HTTP session.

The second form involves creating a webhook object manually using the [`from_url()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Webhook.from_url "discord.Webhook.from_url") or [`partial()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Webhook.partial "discord.Webhook.partial") classmethods.

For example, creating a webhook from a URL and using [aiohttp](https://docs.aiohttp.org/en/stable/index.html "(in aiohttp v3.7)"):
maiden fable
#

!d discord.Webhook.from_url

unkempt canyonBOT
#

classmethod from_url(url, *, session, bot_token=None)```
Creates a partial [`Webhook`](https://discordpy.readthedocs.io/en/master/api.html#discord.Webhook "discord.Webhook") from a webhook URL.
maiden fable
#

Rip am sleepy

fresh orchid
#

Ok so its not possible to add it into the slash command with my method?

maiden fable
#

No. That's not an option type

fresh orchid
#

ok

#

But its possible to add it into the command when you use another method

maiden fable
#

?

fresh orchid
#

In theory its possible to do a select Menu inside a slash command

echo wasp
fresh orchid
#

But not Whit the code i use

tidal hawk
#

My bot has admin but still says: 403 Forbidden (error code: 50013): Missing Permissions after trying to add role

slate swan
maiden fable
#

Smh don't start it rn, already half asleep

maiden fable
maiden fable
#

!d discord.Webhook.send exists

unkempt canyonBOT
#

await send(content=..., *, username=..., avatar_url=..., tts=False, ephemeral=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., view=..., thread=..., wait=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message using the webhook.

The content must be a type that can convert to a string through `str(content)`.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object.

If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") and it must be a rich embed type. You cannot mix the `embed` parameter with the `embeds` parameter, which must be a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects to send.
tidal hawk
slate swan
maiden fable
#

That means the bot doesn't has perms

unkempt canyonBOT
#

@echo wasp, looks like you posted a Discord webhook URL. Therefore, your message has been removed, and your webhook has been deleted. You can re-create it if you wish to. If you believe this was a mistake, please let us know.

maiden fable
#

👀

tidal hawk
slate swan
#

lol what does this error mean? i'm trying to make a bot and something is wrong with the token but idk what

Traceback (most recent call last):
  File "/home/jack/Desktop/coding stuff/WaitForMe/main.py", line 15, in <module>
    client.run(TOKEN)
  File "/home/jack/.local/lib/python3.9/site-packages/discord/client.py", line 723, in run
    return future.result()
  File "/home/jack/.local/lib/python3.9/site-packages/discord/client.py", line 702, in runner
    await self.start(*args, **kwargs)
  File "/home/jack/.local/lib/python3.9/site-packages/discord/client.py", line 665, in start
    await self.login(*args, bot=bot)
  File "/home/jack/.local/lib/python3.9/site-packages/discord/client.py", line 511, in login
    await self.http.static_login(token.strip(), bot=bot)
AttributeError: 'NoneType' object has no attribute 'strip'```
formal goblet
#

i am stuck here, it wont show "watch" button, its a rickroll link bot where if you click watch button it redirects you to rickroll vid

formal goblet
#

dont mind self bot its not ruining anything or anybody

maiden fable
#

Seems like u need python_dotenv

echo wasp
#

Ok so i have this right now but i want to be able to send different text everytime like this &updates 'words go here' i have this for my code right now py @commands.command() @commands.has_role(904216810482720808) async def updates(self): webhook = Webhook.from_url('url here', session=session) await webhook.send('testing message')

slate swan
slate swan
#

that's why i'm confused

fluid spindle
#

Does anyone know how I could use Modals with regular commands? I don't wanna use slash commands.

maiden fable
#

With views

#

Just like how u use bittons

#

Buttons

#

Anyways I'm just gonna go crash already half sleeping cya

olive osprey
#

Hello, so i'm basically currently working on some buttons, stuff and i'm using the discord-components library. I'm just trying to send a message, when the one who isn't the one who performed the command clicks the buttons. It does simply say "interaction failed" when someone else then the author uses the button, but i want it to send a custom error message.

@bot.command()
async def test(ctx):
  embed = discord.Embed(title="test", description="test 2")
  msg = await ctx.send(embed=embed, components=[[Button(style=ButtonStyle.green, label="test1"), Button(style=ButtonStyle.blue, label="test2")]])
  while True:
      res = await bot.wait_for("button_click", check=lambda inter: inter.user == ctx.author)
      if res.component.label == "test1":
        embed2 = discord.Embed(title="asd2yk", description="asd2yk")
        await res.respond(type=7, embed=embed2)
        pass
      elif res.component.label == "test2":
        embed = discord.Embed(title="asd", description="asd")
        await res.respond(type=4, content="Hello", ephemeral=True)
        pass
fluid spindle
slate swan
rotund nova
#

why i have this shit? yesterday i have normal

#

i already pip install asyncio, discord itd.

slate swan
#

Python versions

slate swan
rotund nova
vocal snow
#

pip install asyncio?

rotund nova
vocal snow
#

why

#

asyncio is in stdlib

slate swan
# rotund nova yes

lol pylance can be a jerk with installed packages, if the code runs just fine, then ignore it because pylance is dumb

dusty tapir
#

hi guys how to add buttons to embed

rotund nova
slate swan
fluid spindle
rotund nova
slate swan
fluid spindle
slate swan
dusty tapir
#

ok

rotund nova
#

iooo

#

i got this

fluid spindle
olive osprey
fluid spindle
#

no problem

slate swan
#

Use a fork or dpy 2.0

rigid island
#

as saving each graph it kinda tough

dusty tapir
#

and there is no way to add buttons to embed in discordpy?

fluid spindle
echo wasp
#

hello again, What did i do wrong it is not sending though the webhook and no error in console py @commands.command() @commands.has_role(904216810482720808) async def updates(self, arg): webhook = Webhook.from_url('url here', session=session) await webhook.send(arg)

slate swan
rigid island
dusty tapir
slate swan
#

!d discord.ext.commands.Context.send

fluid spindle
slate swan
#

!d disnake.ext.commands.Context.send

unkempt canyonBOT
#
await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

To upload a single file, the `file` parameter should be used with a single [`File`](https://docs.disnake.dev/en/latest/api.html#disnake.File "disnake.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`File`](https://docs.disnake.dev/en/latest/api.html#disnake.File "disnake.File") objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://docs.disnake.dev/en/latest/api.html#disnake.Embed "disnake.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://docs.disnake.dev/en/latest/api.html#disnake.Embed "disnake.Embed") objects. **Specifying both parameters will lead to an exception**.
slate swan
#
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 312, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 43, in on_message
    await help(message)
  File "main.py", line 169, in help
    await message.channel.send(embed = emHelp)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/abc.py", line 870, in send
    data = await state.http.send_message(channel.id, content, tts=tts, embed=embed, nonce=nonce)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 225, in request
    raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message```
#

what is this?

rigid island
fluid spindle
echo wasp
#

hello again, What did i do wrong it is not sending though the webhook and no error in console py @commands.command() @commands.has_role(904216810482720808) async def updates(self, arg): webhook = Webhook.from_url('url here') await webhook.send(arg) i attempted and failed

fluid spindle
rigid island
rigid island
#

really imp to get the graph

#

thats the main part

#

in my bot

fluid spindle
#

Instead of saving the the binary data to a file, you can directly convert it to PNG/JPEG and throw it in as the Embed file

rigid island
#

yeahhh but where i save or store all this jpeg files?

fluid spindle
#
from matplotlib import pyplot as plt
from io import BytesIO

plt.plot([],[])
data_obj = BytesIO()
plt.savefig(data_obj, format='png')
pngFile = discord.File(BytesIO(data_obj.getvalue()),filename="name.gif")
ourEmbed = discord.Embed(file=pngFile)
await ctx.send(embed=ourEmbed)
fluid spindle
rigid island
#

thanku, let me try

next breach
#

hi, i'm really struggling to workout how to store a date and time using datetime in a json file for when a user joins my server. would really appreciate the help 🙃

slim ibex
#

not the json as a database

next breach
#

i'm storing other things in the json file like user warnings and want the user to be able to request this data using a bot command which has worked for the warnings but not this datetime stuff

slim ibex
#

a_datetime = datetime.datetime.now()

formatted_datetime = a_datetime.isoformat()
json_datetime = json.dumps(formatted_datetime)
#

you could prolly simplify this

#

But pls don’t use JSON as a database

next breach
#

what would you recommend instead to allow the user to access it using a bot command?

slim ibex
#

user accessing a database?

#

if that’s the case then it’s unsecured

#

all the user can do is create a query when they run a command not actually access the database

#

use an RDBMS like SQLite instead of json

next breach
# slim ibex user accessing a database?

no, so what happens is they send a command and the bot provides the data that's under their name in an embed but not all of the data. Only the data that applies to them

slim ibex
#

id word it better but ok

#

idk how to do that with json. Prolly read the file and find the data

#

it might be hard to find info for the specific user which is why you use a rdbms

#

it’s easier to fetch the users specific info in their record with rdbms

next breach
slim ibex
#

What’s hard about it

next breach
#

never mind, working perfectly now thx

slim ibex
#

oh ok

echo wasp
#

Hello, Who know about webhooks in bots?

rigid island
fluid spindle
#

Wow. It worked!
No problemo

pliant gulch
#

You should keep in mind, as the graph gets more complex, it will take longer to build. And the long it takes to build, the longer your bot will be blocked as matplotlib is a sync library

#

If you block long enough, your bot will just disconnect as it won't be able to send heartbeats

fluid spindle
#

You're right.

#

Is there not an asynchronous version matplotlib?

pliant gulch
#

Nope, but you can run all your code inside of an executor

naive spoke
#

vs code

left crater
#

that was delayed...

naive spoke
#

ye i was busy

slate swan
#

how does ctx.invoke with kwargs work, what is a mapping, how to form a mapping? cant find it..., thanks

slim ibex
#

!d discord.ext.commands.Context.invoke

unkempt canyonBOT
#

await invoke(command, /, *args, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Calls a command with the arguments given.

This is useful if you want to just call the callback that a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") holds internally.

Note

This does not handle converters, checks, cooldowns, pre-invoke, or after-invoke hooks in any matter. It calls the internal callback directly as-if it was a regular function.

You must take care in passing the proper arguments when using this function.
slim ibex
#

**kwargs just represents your own keyword arguments

slate swan
#

can you provide an exmaple?

naive spoke
#

?

left crater
#

show the full error

slate swan
#

i got it working now, thanks!

naive spoke
# left crater show the full error

ord\ext\commands\core.py", line 863, in invoke await injected(*ctx.args, **ctx.kwargs) File "C:\Users\udaya\AppData\Roaming\Python\Python37\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: CommandRegistrationError: The command VVD is already an existing command or alias.

left crater
#

bruh

#

it says there is a command by that name

#

look for it

left crater
naive spoke
#

i said ?mood

#

and it says that

slim ibex
#

prolly timed out

left crater
#

async def moodd():

naive spoke
slim ibex
#

no just after the commands up for too long without any interactions it will prolly time out

naive spoke
# left crater ```async def moodd():```

now it says this Traceback (most recent call last): File "C:\Users\udaya\AppData\Roaming\Python\Python37\site-packages\discord\ext\commands\bot.py", line 939, in invoke await ctx.command.invoke(ctx) File "C:\Users\udaya\AppData\Roaming\Python\Python37\site-packages\discord\ext\commands\core.py", line 863, in invoke await injected(*ctx.args, **ctx.kwargs) File "C:\Users\udaya\AppData\Roaming\Python\Python37\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: 'builtin_function_or_method' object has no attribute 'choice'

#

now it says dis

final iron
#

I think its pretty clear

slim ibex
#

Don’t specify a timeout

#

It defaults to None

naive spoke
final iron
#

So...?

slim ibex
#

Show me code

#

no __init__ method?

naive spoke
final iron
naive spoke
#

this and kk is my list

dense coral
#

This button does not work, move to py @bot.event on_button_click

slim ibex
#

indent the super().__init__() into the __init__

fresh orchid
#
message = await send('Which component chart would you like to view? Respond with "CPU", "GPU", "RAM" or "all" (20s)', view=view)

        async def button_cpu_callback(interaction:discord.Interaction):
            await message.delete()

I get an error because interaction have no atribute delete

is there any way to delete the old message when I use the button
Or is there a way to edit

slim ibex
#

I responded

slate swan
#
    bot = discum.Client(token=firstline)


    def close_after_fetching(resp, guild_id):
        if bot.gateway.finishedMemberFetching(guild_id):
            lenmembersfetched = len(bot.gateway.session.guild(guild_id).members)
            print(str(lenmembersfetched) + ' members fetched')
            bot.gateway.removeCommand({'function': close_after_fetching, 'params': {'guild_id': guild_id}})
            bot.gateway.close()


    def get_members(guild_id, channel_id):
        bot.gateway.fetchMembers(guild_id, channel_id, keep='all', wait=1)
        bot.gateway.command({'function': close_after_fetching, 'params': {'guild_id': guild_id}})
        bot.gateway.run()
        bot.gateway.resetSession()
        return bot.gateway.session.guild(guild_id).members


    members = get_members(server, channel)
    memberslist = []

    for memberID in members:
        memberslist.append(memberID)
        print(memberID)

    f = open('logs/membersIDs.txt', "w")
    for element in memberslist:
        f.write(f'{element}' + '\n')
    f.close()

    print(f'{Fore.LIGHTRED_EX}gettingmembers now{Fore.RESET}')
    time.sleep(2)

    file = open("logs/membersIDs.txt", "r")

yo can someone help it gives me error i just want it to save members ids

unkempt canyonBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

slate swan
#

how does it break laws

final iron
slate swan
final iron
#

Yeah, sure

slate swan
#

I mean it

kindred drum
#

Hey! py @commands.has_permissions(administrator=True) @commands.command(name="cban") async def cban(self, ctx, member: discord.User, reason:str, proof:str): try
how would I go about error handling something like this?
try:
except:
doesn't work for some reason

slate swan
cold sonnet
#

absolutely bad

slim ibex
#

timeout=None

cold sonnet
#

disgusting

final iron
#

But sure, "you didn't know"

left crater
#

whats the error

pliant gulch
#

Crazy, people still actually selfbot and use discum

kindred drum
#

how would I do that

left crater
#

u can use isinstance()

slate swan
#

Hello I’m looking for tutoring python ik the very basics

#

Depending on price I’ll pay

final iron
unkempt canyonBOT
#

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

final iron
#

And this isn't the correct channel

slate swan
final iron
#

Mhm

slate swan
#

I would feel bad not paying someone for teaching me something

left crater
#

bro just google free python lmao

slate swan
left crater
#

thats how most people learn

slate swan
#

@left crater yes but tutors can help if you get stuck

#

When your learning the tutor could help you improve code

left crater
#

ever heard of stack overflow?

slate swan
slate swan
final iron
final iron
slate swan
left crater
#

or do some coding boot camps

slate swan
left crater
#

codecademy is really good

fervent shard
#
@bot.listen()
async def on_message_delete(message):
  embed=discord.Embed(description=f"")
  embed.set_author(name=message.author.name, icon_url=message.author.name.avatar_url)
  channel=bot.get_channel(943385924052602880)
  await channel.send(channel, embed=embed)```error:
```  File "main.py", line 35, in on_message_delete
    embed.set_author(name=message.author.name, icon_url=message.author.name.avatar_url)
AttributeError: 'str' object has no attribute 'avatar_url'```
slate swan
final iron
#

This server is for everyone. Beginner to advanced

slate swan
#

advanced to god

fervent shard
final iron
left crater
slate swan
# slate swan advanced to god

lol i’d agree with this if they didn’t help with basics too!! but it does seem like most everyone here is >>>>>>>>

#

lol

slate swan
final iron
#

And I don't

slate swan
cold sonnet
fervent shard
naive spoke
final iron
#

And did you import random?

slate swan
#

oops

naive spoke
naive spoke
slate swan
#

^^^^^^^^

slate swan
#

why do i have this? is it a glitch?

final iron
slate swan
final iron
#

Or you just edited the html

slate swan
#

what is thml?

final iron
#

Either way, it's off topic

slate swan
#

html*

left crater
#

its sending the channel and the embed

slate swan
#

😏

#

🤤

#

i am racist

novel sinew
slate swan
final iron
slate swan
#

nvm

final iron
#

Thanks

slate swan
final iron
#

Mhm

naive spoke
#

do people need to know regular python before moving into discord.py?

naive spoke
#

ok

#

well im not other people ig

final iron
left crater
slate swan
final iron
#

I don't know what you want me to say

slate swan
final iron
#

No

slate swan
#

sure

vale wing
#

That channel doesn't have a category

cold sonnet
final iron
#

The category is None

vale wing
#

You should add a simple if condition that would check if the category is None

slate swan
#

What is best way to learn python from any good python coders

#

Maybe @final iron ^

final iron
#

!resources

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

vale wing
#

You can't learn python from coders unless they teach you?

pallid marsh
slate swan
#

Ok I don’t think your much help if you can’t use command XD

vale wing
#

Basic programming principles, just syntax won't do that

slate swan
#

So it doesn’t really help

pallid marsh
vale wing
#

Ok

fervent shard
slate swan
fervent shard
#

i see it now

slate swan
#

Like basic syntax and errors

vale wing
#

Now onto OOP

slate swan
#

And imports and strings simple discord bots ect

pallid marsh
slate swan
#

Could you try describe

vale wing
#

Object oriented programming for example

#

Classes, methods, etc

pallid marsh
#

^

slate swan
vale wing
#

You should learn at least functional programming to start with discord bots

#

But OOP is required if you wanna do better bots

pallid marsh
vale wing
#

I call it functional

pallid marsh
#

Ah same difference ig

slate swan
#

I understand it to a standard

pallid marsh
#

do you know any other languages or only py?

vale wing
slate swan
#

I tried node and gave up

slate swan
#

That’s gibberish trying to type XD

pallid marsh
vale wing
#

I prefer py but I also know C# and Java

#

(java is ugly but good)

pallid marsh
#

I know py, lua, js and the tiniest tiniest bit of C++

slate swan
slate swan
pallid marsh
slate swan
vale wing
#

JS is quite easy but most of tutorials don't teach you how to make it interact with sites

slate swan
#

its good but hard

vale wing
slate swan
vale wing
#

Low-level is hard 😳

vale wing
#

But I learned it like 3 times

#

And never used anywhere

slate swan
#

What’s the best approach

vale wing
#

Yeah you should learn the overall principles of programming from it and then get to other languages

slate swan
#

So once I get use to python it should make other languages less hustle

slate swan
#

And there’s loads of ways to approach python

vale wing
#

Yes

slate swan
#

are they any videos u recommend

#

cuz i wanna learn it

vale wing
#

I just read course from stepik

slate swan
#

Can I have someone’s deep honest opinion how did you all learn python (don’t say !reasources)

vale wing
#

Never watched youtube tutorials

vale wing
slate swan
slate swan
slate swan
vale wing
#

For python*

slate swan
#

Can I have someone’s deep honest opinion how did you all learn python (don’t say !reasources)

vale wing
#

Only did that for like "How to setup ad in Unity"

jade dune
slate swan
pallid marsh
slate swan
#

@slate swan what is "scythe 2.0"

final iron
vale wing
#

As for the courses platforms, personally I recommend Sololearn and Stepik, those are the ones I used

jade dune
jade dune
#

also if I'm asking in the wrong place feel free to hit me with a stick and then point at the correct channel

vale wing
jade dune
potent spear
jade dune
naive spoke
vale wing
#

Selfbot breaks the discord ToS, so we don't help with this

potent spear
# jade dune gotcha. any suggestions?

use a discord bot and try to learn how to code one which has similar features

  1. it's not that hard once you get the hang of it
  2. the bot has to be in said guild
  3. you'll learn some nice skills
jade dune
#

the bot has to be in the guild?

potent spear
#

yes, ofc
otherwise it can't see the channels etc

jade dune
#

unfort
thanks

slate swan
slate swan
#

As it kinda has malicious purpose

#

😟

slate swan
slate swan
#

It shows how to get your discord token

slate swan
#

what should i choose

#

@vale wing

potent spear
#

you're asking this in a python server?

slate swan
slate swan
#

im not asking u

potent spear
#

have fun trying to get an answer anywhere about that here

rare saddle
#

How to make the slash command available only to a specific role

slate swan
rare saddle
slate swan
#

then i dont know

slim ibex
#

!d disnake.ext.commands.has_role

unkempt canyonBOT
#

@disnake.ext.commands.has_role(item)```
A [`check()`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.check "disnake.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.

If a string is specified, you must give the exact name of the role, including caps and spelling.

If an integer is specified, you must give the exact snowflake ID of the role.

If the message is invoked in a private message context then the check will return `False`.

This check raises one of two special exceptions, [`MissingRole`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.MissingRole "disnake.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.NoPrivateMessage "disnake.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.CheckFailure "disnake.ext.commands.CheckFailure").

Changed in version 1.1: Raise [`MissingRole`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.MissingRole "disnake.ext.commands.MissingRole") or [`NoPrivateMessage`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.NoPrivateMessage "disnake.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.CheckFailure "disnake.ext.commands.CheckFailure")
potent spear
#

only works with interactions, not sure

slim ibex
#

don’t think ephemeral is a arg of send()

final iron
#

You can only use ephemeral messages in interactions

slim ibex
#

^

rare saddle
slim ibex
unkempt canyonBOT
#

@disnake.ext.commands.has_permissions(**perms)```
A [`check()`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.check "disnake.ext.commands.check") that is added that checks if the member has all of the permissions necessary.

Note that this check operates on the current channel permissions, not the guild wide permissions.

The permissions passed in must be exactly like the properties shown under [`disnake.Permissions`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions "disnake.Permissions").

This check raises a special exception, [`MissingPermissions`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.MissingPermissions "disnake.ext.commands.MissingPermissions") that is inherited from [`CheckFailure`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.CheckFailure "disnake.ext.commands.CheckFailure").
slim ibex
#

put administrator=True to make it only run if the person has administrator perm

final iron
#

Oh disnakes partnership worked out

rare saddle
final iron
#

Docs are different now

final iron
#

Looks really nice tbh

slim ibex
#

Ye it does

rare saddle
slim ibex
#

I was talking to @final iron

#

but ok np

slate swan
final iron
slate swan
#

!d discord.Message.edit

unkempt canyonBOT
#

await edit(content=..., embed=..., embeds=..., attachments=..., suppress=..., delete_after=None, allowed_mentions=..., view=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the message.

The content must be able to be transformed into a string via `str(content)`.

Changed in version 1.3: The `suppress` keyword-only parameter was added.
slate swan
bold surge
#

disnake's been gaining a lot of traction lately

slate swan
#

yup

#

pretty great

slim ibex
#

it’s a rly good lib

#

but hikari/pincer still looking better

slate swan
#

yes

#

best fork disnake
best discord api wrapper would be hikari

slim ibex
#

pincer 🗿

final iron
#

rin is better

slim ibex
#

^

slate swan
#

i mean the collectors are clean imo

slim ibex
#

rin is better than any lib that will ever exist

slate swan
#

made by someone who has read the python zen

slim ibex
#

🗿

slate swan
slate swan
unkempt canyonBOT
#

class discord.Embed(*, colour=Embed.Empty, color=Embed.Empty, title=Embed.Empty, type='rich', url=Embed.Empty, description=Embed.Empty, timestamp=None)```
Represents a Discord embed.

len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

bool(b) Returns whether the embed has any data set.

New in version 2.0.

Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty").

For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
slim ibex
#

wat

slate swan
#

the ansi buildesrs

rare saddle
#

@slim ibex For some reason, the command did not become darkened and inaccessible, it just wrote that an admin panel was needed

slate swan
final iron
#

okimii what do you think about the new modals

slim ibex
slim ibex
slate swan
slate swan
final iron
#

🗿

slim ibex
#

oh no I haven’t

#

send em over

slate swan
bold surge
slate swan
#

🗿

slim ibex
#

oh ok

bold surge
#

not sure if disnake has that feature tho

slim ibex
#

💀

final iron
#

Okimii can we work on akeno canary

slate swan
slate swan
#
@command()
    async def ban(
        ctx: Context,
        member: Member = None,
        deletemsgs: int = 1,
        *,
        reason: str = "no reason provided",
    ) -> Optional[Message]:
        if not member:
            return await ctx.reply("You must specify a member to ban")
        elif member.id == ctx.author.id:
            return await ctx.reply("You cannot ban yourself")
        try:
            await member.send(
                embed=Embed(
                    title="Ban",
                    description=f"You have been banned from: {ctx.guild}\n reason: {reason}\n by: {ctx.author.name}",
                    color=0xA020F0,
                    timestamp=datetime.now(),
                )
            )
        except Forbidden:
            await ctx.reply("Could not dm member")
        await member.ban(delete_message_days=deletemsgs, reason=reason)
        await ctx.reply("Member has been banned")

first command

tacit storm
rare saddle
slim ibex
slate swan
potent spear
tacit storm
slate swan
slim ibex
#

what is this akeno canary bot for

final iron
slate swan
final iron
#

I'll contribute

slate swan
potent spear
#

most likely, member isn't what you think it is

slim ibex
#

nah bro

slate swan
#

context doesnt have that attr?

tacit storm
#

i know the problem

slim ibex
#

the fuck

tacit storm
#

@slate swan so, question,

how familiar are you with OOP?

slim ibex
#

Be respectful

tacit storm
daring olive
slim ibex
#

Object oriented programming

potent spear
tacit storm
#

object orientated programming.

pliant gulch
final iron
#

@slate swan Make a repo on github for akeno canary

tacit storm
#

well, then again, you'd know since it's in a class, it needs self as an paramater before anything else.

slate swan
slim ibex
pliant gulch
#

Discord ANSI codeblocks don't support RGB codes, or 255 colour codes

daring olive
#

!warn 894794517079793704 being dismissive of our users is unacceptable. language like "everyone stfu" and "if you were familiar in any sense" is not welcoming for a learning environment that we aim to be. read and follow our #rules and #code-of-conduct before proceeding to participate on the server

potent spear
unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied warning to @tacit storm.

pliant gulch
#

Only 8-16 and only the regular ones

#

Not even bright colour codes for the 8-16 colours are supported

pliant gulch
#

😔

potent spear
slate swan
#

well?

cerulean olive
#

oh shit

#

wrong pic

slate swan
final iron
slate swan
potent spear
final iron
potent spear
#

did you read the error tho? xd

slim ibex
#

^

slate swan
#

i mean yeah you have a point

potent spear
#

what did you learn from it?

slate swan
potent spear
#

that's correct
it's role.mention, not roles.mention

manic wing
#

@pliant gulch are you a strong believer in subclassed help commands?

slim ibex
#

Then something is wrong with your list contents I guess

potent spear
#

which?

pliant gulch
slate swan
rare saddle
#

How to make some slash commands inaccessible to people without a specific role as in the photo, the command in the middle is not available to me, but on the sides are available. Library - disnake

manic wing
slim ibex
#

I’m a believer in subclassing to create your Bot instance

manic wing
#

i want to have an argument with someone who believes every help command must be subclassed

slate swan
potent spear
slim ibex
#

This dude

manic wing
#

bro pinged everyone 😢

slim ibex
#

LMAO

slate swan
slim ibex
#

Don’t download it’s prolly a fucking Trojan horse

manic wing
slate swan
#

🏃

slim ibex
#

It isn’t necessary

potent spear
slim ibex
#

it helps though with different methods that you won’t have without subclassing

pliant gulch
final iron
#

How does discord.py allow you to access the User object with discord.User?

#

To my understanding you should only be able to access it with discord.user.User

final iron
#

Oh

slate swan
#

iirc init files are used so all the files are one package probably wrong***

pliant gulch
#

Namespace file

slate swan
boreal ravine
#

!d discord.abc.Messageable.send embeds kwarg

unkempt canyonBOT
#

await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
manic wing
pliant gulch
slate swan
manic wing
#

youre just a believer in scaleable in procedural, which is not necessarily subclassed help

pliant gulch
#

I must be mistaking your version of whatever help command eachother are talking about

#

I'm assuming you are talking about some help command that isn't technically a subclassed helpcommand, but it instead just grabs the commands, etc procedurally

pliant gulch
manic wing
#

im talking about the difference between literally subclassing commands.HelpCommand versus making a command

pliant gulch
slate swan
pliant gulch
#

Sure

slate swan
#

bro dont say sure it makes me feel wrong

modest plover
#

I tried to make a timeout command and keep getting an error. Any help?

import disnake
from disnake.ext import commands

class Timeout(commands.Cog):
  """Mutes/timeouts a user."""
  
  def __init__(self, bot: commands.Bot):
    self.bot = bot
  
  async def timeout(self, inter, user: disnake.Member, until = int, reason = None):
    """Mutes/timeouts a member for up to 28 days in the future."""
    await disnake.timeout(*, duration=until, member=user, reason=reason)
  
def setup(bot):
    bot.add_cog(Timeout(bot))
#
Traceback (most recent call last):
  File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/disnake/ext/commands/common_bot_base.py", line 416, in _load_from_module_spec
    spec.loader.exec_module(lib)  # type: ignore
  File "<frozen importlib._bootstrap_external>", line 879, in exec_module
  File "<frozen importlib._bootstrap_external>", line 1017, in get_code
  File "<frozen importlib._bootstrap_external>", line 947, in source_to_code
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "/storage/emulated/0/coding/python/harmony/commands/timeout.py", line 12
    await disnake.timeout(*, duration=until, member=user, reason=reason)
                           ^
SyntaxError: invalid syntax

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

Traceback (most recent call last):
  File "/storage/emulated/0/coding/python/harmony/maindev.py", line 11, in <module>
    bot.load_extensions("commands")
  File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/disnake/ext/commands/common_bot_base.py", line 603, in load_extensions
    self.load_extension(extension)
  File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/disnake/ext/commands/common_bot_base.py", line 488, in load_extension
    self._load_from_module_spec(spec, name)
  File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/disnake/ext/commands/common_bot_base.py", line 419, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
disnake.ext.commands.errors.ExtensionFailed: Extension 'commands.timeout' raised an error: SyntaxError: invalid syntax (timeout.py, line 12)

That's the error

final iron
modest plover
#

I didn't...?

#

I looked at the docs, and then wrote this

#

I haven't had to anything with any user management so bans, kicks, timeouts, role changing, etc

#

I ain't got a clue what I'm doing

potent spear
pliant gulch
potent spear
#

try and see I'd say
you could also perfectly do append, instead of creating the list at the end

#

seems good to me

#

make sure it's a correct url
you should TEST with one embed first

potent spear
#

concrete code?

slate swan
#

pep 420😳

pliant gulch
potent spear
#

can you add something extra to the footer?

slate swan
rotund creek
#

Is there something like a checkbox

#

Like multiple choice checkbox

slate swan
#

a what

cedar stream
rotund creek
#

I thought select menu was only 1

slate swan
#

no

cedar stream
rotund creek
#

Alr thanks ill give it a try

cedar stream
#

Lmao hi @potent spear

cedar stream
rotund creek
#

Yeay

cedar stream
#

Docs

rotund creek
#

Yeah

potent spear
#

there you go

#

doesn't it fit in one embed tho? the 2 apart seemed pretty sketchy

boreal ravine
#

Try it and see ✨

rotund creek
#

Anyone know any good videos for pycord selectmenus

potent spear
#

it's good to know what's possible, but don't implement their code

rocky trench
#

Indeed. Tutorials aren't good. U only learn to use things for 1 specific usage

rotund creek
#

Docs are not even that explained

#

No examples either

potent spear
pliant gulch
potent spear
#

this doesn't explain buttons and other new stuff tho

potent spear
rare saddle
#

How to give access to slash command using - default_permission = False ?

pliant gulch
potent spear
rocky trench
#

The docs are pretty easy to get, if u get 1 example of them

cedar stream
#

It just disables the command

#

Like idk what it does

rocky trench
#

Anyways, @potent spear is it me or is there a possibility to hide some slash commands for people without admin?

rare saddle
pliant gulch
#

But I could be very well wrong

cedar stream
rocky trench
rare saddle
cedar stream
#

In my opinion

potent spear
rocky trench
#

Docs could use some examples tbh

#

I had a hard time when I first started dpy

potent spear
rocky trench
#

Yh indeed

cedar stream
potent spear
rare saddle
cedar stream
cedar stream
#

The edit

rare saddle
sullen linden
#

im using nextcord, is there a way to delete an ephemeral interaction message after im done responding to it?

cedar stream
potent spear
cedar stream
#

Works with all forks

potent spear
#

hold up, can you even reply to an ephemeral message as a bot?
I don't do any of this v2+ stuff

sullen linden
cedar stream
pliant gulch
cedar stream
potent spear
potent spear
#

ayo, not bad

pliant gulch
#

And they announced it with pictures on the first day of release

potent spear
#

missed that

#

API wrapper docs > discord API docs

cedar stream
#

I remember when I fucked with how to receive messages without api wrapper

#

It’ s when I discovered websockets

#

Didnt find anything in the docs

potent spear
#

it's probably a sort of 'tunnel' between the client and server without the need of verification every time?

cedar stream
cedar stream
#

Well in discord docs It’ s under getaways and I never bothered to check until recently

potent spear
cedar stream
#

So immediately when server sees there is a message for u it will send it to yoy

#

You

potent spear
pliant gulch
#

Saves a lot of performance from hella API calls

cedar stream
#

You wont need to ask the server if you have a message

pliant gulch
#

When it comes to messaging apps

cedar stream
#

It will send it to u

cedar stream
pliant gulch
potent spear
pliant gulch
#

For discord's gateway you send a IDENTIFY payload with your token

cedar stream
pliant gulch
#

Then later on for reconnect payloads you use the session_id given to you in the response of the IDENTIFY Payload

cedar stream
potent spear
potent spear
unkempt canyonBOT
#

rin/gateway/handler.py lines 173 to 186

@property
def identify(self) -> IdentifyPayload:
    return {
        "op": 2,
        "d": {
            "token": self.client.token,
            "intents": self.intents.value,
            "properties": {
                "$os": "",
                "$browser": "Rin 0.1.0-alpha",
                "$device": "Rin 0.1.0-alpha",
            },
        },
    }```
pliant gulch
#

You send it to discord's gateway as your first payload

#

Then afterwards you send heartbeats at intervals to keep the connection "alive"

cedar stream
potent spear
cedar stream
potent spear
#

this reminds me of Twitch, with how they keep track if you still watching

#

apparently you send a post req to the server every minute watched

cedar stream
potent spear
cedar stream
#

U gotta do it how discord wants it

pliant gulch
pliant gulch
cedar stream
pliant gulch
#

Yes

potent spear
#

or am I just completely off?

pliant gulch
#

Yes, that's the gateway

#

The websocket one

potent spear
#

what type of api is that?

cedar stream
#

Websocket 🤷🏼‍♂️

pliant gulch
#

Not sure what to call it other than a stateful API

#

Or a protocol, could be either

potent spear
#

seems like I heard that before tho

#

stateful

#

so that's mostly where you want some bot or whatever to "stay online", right?

cedar stream
#

It just means it stores some state and if the server restarts you can’t continue from the same point

pliant gulch
#

As soon as your bot finishes the first connection to discord, so as long as the heartbeats are sent you bot will be in a "connected" state

#

It will have a presence, notably

pliant gulch
#

I really should rewrite my wrappers gateway code again

#

I don't like how it looks

potent spear
#

does this "keep alive" loop have some kind of if statement as first check?
and when the bot closes, it becomes false and shuts the whole thing down? or is there some other structure involved?

pliant gulch
#

You send the heartbeat, if discord got it within the timeframe it will acknowledge your bot as being alive. Once you stop sending heartbeats within the timeframe discord will just disconnect you from the gateway

#

You may also be disconnected from the reconnect opcode

#

Discord also regularly sends resume opcode, you'd have to handle this as well

potent spear
pliant gulch
#

If you stop the bot, you stop the heartbeats

#

At least depending on your wrapper

#

You don't send a request to anything

potent spear
#

aight, the keep-alive just quits, I get tit

pliant gulch
#

The websockets are bidirectional, if the other end doesn't receive something within the timeframe it will know

#

No need for an API call to some other route

potent spear
#

let's say the keep alive has an interval of 30 secs, right?

#

and you shutdown your bot in 15 secs, then HOW does the server know the bot went offline when it actually still has 15 secs left to wait for some req?
or does it actually send a post req with some "I quit" shit in there?

pliant gulch
#

Then you alt tab and see for some reason the bot still has a presence?

#

Then a few seconds later the presence disapears

#

Hope that answered the question

potent spear
#

so you basically wanted to say that it stays online for a little while after

pliant gulch
potent spear
#

what's the correct terminology for the keep alive receiver at the server's end?

potent spear
pliant gulch
#

You should read the RFC for websockets

potent spear
#

that's YT vid worthy

pliant gulch
potent spear
#

yeah, I'm not getting the correct terminology in this, but I get the point mostly

#

since API requests just take too much time/are too much of a hassle, mainly because you're probably sending hundreds at a time
for example with online multiplayer FPS games

pliant gulch
#

Sure, you could say multiplayer FPS games use websockets

#

They use both TCP and UDP protocols iirc

potent spear
#

and UDP is another story ig

rare saddle
#

How to get all people with admin rights on a server?

stone talon
potent spear
rare saddle
potent spear
stone talon
#

I have a question about ffmpeg - using it to play audio from a discord bot.
Error:

Unrecognized option 'reconnect'.
Error splitting the argument list: Option not found

This is my code:

@bot.command()
async def playy(ctx, url):
    channel = ctx.message.author.voice.channel
    FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5',
                      'options': '-vn'}
    vc = await channel.connect()
    player = await vc.play((discord.FFmpegPCMAudio("videos/piano.mp3", **FFMPEG_OPTIONS)))
    player.start()
  1. My ffmpeg is up-to-date
  2. The rest of my code runs good (i shoved print statements between each line)
  3. Other modules are also uptodate
potent spear
stone talon
potent spear
stone talon
potent spear
#

are those even up-to-date?

stone talon
#

wait

#

i think so...

#

lemme cehcjk

stone talon
#

🙏

potent spear
#

as the answer states...

stone talon
#

i have been trying to figure out the error for 4 hrs now

#

lmao

stone talon
potent spear
stone talon
potent spear
stone talon
#

nods head

slate swan
#

can someone familiar with discord.py dm me so i can show them this code? i'm not sure if it's to steal discord tokens or not but it's hidden at the bottom of this code i found...

final iron
#

Yes this does steal tokens

#

As far as I can understand

slate swan
#

ahaha thats what i thought

#

ty

hoary cargo
#

Interesting, no fight today

wicked atlas
final iron
#

I'll start something

#

Joke btw

#

Don't warn me moderators

bold surge
slim ibex
#

hot take: ||disnake is bad||

#

thjis should start something

bold surge
#

hotter take: ||pycord is good||

slim ibex
bold surge
#

this should really start a war now

final iron
hoary cargo
#

Now prepare

slim ibex
#

even hotter take: ||discord.js better||

bold surge
#

!ban

hoary cargo
slim ibex
#

🗿

hoary cargo
#

🗿 wow

bold surge
#

oh nahh

pliant gulch
#

When people find out the original name of discord.py was PyDiscord

hoary cargo
#

They just moved the py

final iron
#

Smart

#

!pypi PyDiscord

unkempt canyonBOT
final iron
#

Discordian

slim ibex
#

💀

hoary cargo
#

Lmao
Sounds like an old language from 5k years ago used by Discordian people

#

They had discordian villages

snow ibex
hoary cargo
#

Should we make a wiki page about the great discord python Schism

final iron
#

Someone just watched some halo lore

maiden fable
#

?

final iron
#

What

steel void
#

have anyone used the webhooks to setup a way for users to vote for your bot to earn rewards?

#

Im completely lost

hoary cargo
# final iron Am I correct?

MultiHmm in fact no, I know about the Great Schism because yk, History and religion, but you made me curious so I looked up to halo's Great Schism, much more entertaining kekwboom

final iron
#

I thought I found a fellow halo lore enjoyer

hoary cargo
#

sadFumo doom

final iron
#

Doom is also good but halo is better

nimble plume
#

!variable

final iron
maiden fable
unkempt canyonBOT
#

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

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

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

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

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

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

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 floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

final iron
#

People aren't going to click on a random link

slate swan
#

Bruh

slim ibex
#

lmao I've seen that vid

final iron
slim ibex
#

#discordpy #python #tutorial

Welcome to the fourteenth episode of my Discord PY Tutorial Series where I go through and explain how to create a full on levelling system using aiosqlite for a database.

Thank you for watching! If you enjoyed, please subscribe as 99% of my viewers aren't and it means a lot as I am trying to grow. Also comment any ...

▶ Play video
final iron
#

lmao

slim ibex
#

shit i feel bad exposing

#

💀

final iron
#

🗿

maiden fable
#

Nvm I won't say anything

slate swan
#

I just wanted to know if it was the correct way

#

Cuz tutorials like this are known to be bad

slim ibex
#

True

hoary cargo
#

Well
Tutorials are not for copy pasting but more of getting inspiration this is how I see them

slim ibex
#

^

pliant gulch
#

I personally never watch tutorials, it’ll just make all my ideas and projects generic

glossy ocean
#

anyone familiar with music bots?

final iron
#

mhm

glossy ocean
#

the one im working on isnt recognizing commands

#

but i have them defined

grim coral
#

I just started to code a Discord bot but when I start to code all I have is
*import discord

class MyClient(discord.Client):
async def on_ready(self):
print('Logged on as {0}!'.format(self.user))

async def on_message(self, message):
    print('Message from {0.author}: {0.content}'.format(message))

client = MyClient()
client.run('TOKEN')*

But when I want to make commands do I put the command code on a different slide from the normal code or put the command code onto a normal command?

slim ibex
#

!code

unkempt canyonBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

grim coral
#

Its hard to explain

glossy ocean
#

'''py
@commands.command()
async def join(self,ctx):
if ctx.author.voice is None:
await ctx.send("You gotta be in vc idiot")
voice_channel = ctx.author.voice.voice_channel
if ctx.voice_client is None:
await voice_channel.connect()
else:
await ctx.voice_client.move_to(voice_channel)
'''

slim ibex
#

It derives from Client

glossy ocean
#

???

slim ibex
#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.

This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.

This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
unkempt canyonBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

glossy ocean
#
 @commands.command()
    async def join(self,ctx):
      if ctx.author.voice is None:
        await ctx.send("You gotta be in vc idiot")
      voice_channel = ctx.author.voice.voice_channel
      if ctx.voice_client is None:
        await voice_channel.connect()
      else:
        await ctx.voice_client.move_to(voice_channel)
#

when i run it it claims join is not a command

sick birch
#

If you have the id you can do await bot.get_channel(id).send(...)

vocal snow
sick birch
#

So what are you trying to accomplish? Like what feature?

#

What function? A check?

glossy ocean
sick birch
#

Yes, but context is important for us to understand

vocal snow
sick birch
#

just saying "can i use ctx outside" is not helpful, for example, if you are using a check we can tell you that checks provide you with a ctx

final iron
#

You don't have to add commands

vocal snow
#

No, that's the bot.command decorator

final iron
sick birch
#

In that case, if it's a check, it does provide you with the ctx, this is the example from the docs:

async def is_owner(ctx):
    return ctx.author.id == 316026178463072268

@bot.command(name='eval')
@commands.check(is_owner)
async def _eval(ctx, *, code):
    """A bad example of an eval command"""
    await ctx.send(eval(code))
vocal snow
#

Yes, but then you still need to add the cog to the bot

glossy ocean
final iron
sick birch
#

Alternatively,

def is_owner():
    async def predicate(ctx):
        return ctx.author.id == 316026178463072268
    return commands.check(predicate)

@bot.command(name='eval')
@is_owner()
async def _eval(ctx, *, code):
    """A bad example of an eval command"""
    await ctx.send(eval(code))
#

You have access to ctx and all it's methods, such as ctx.send() from within that function

#

ctx.channel

#

Looks like you already have it as well

#

Which it is

#

Course you can

glossy ocean
final iron
glossy ocean
vocal snow
glossy ocean
#

so no?

sick birch
#

Yes, dev_check() is provided the ctx

vocal snow
glossy ocean
sick birch
#

It throws an error at async def dev_check(ctx):?

#

Then where and what error is it throwing?

vocal snow
sick birch
#

And what error is it throwing?

glossy ocean
#
class music(commands.Cog):
sick birch
#
async def is_owner(ctx):
    return ctx.author.id == 316026178463072268

@bot.command(name='eval')
@commands.check(is_owner)
async def _eval(ctx, *, code):
    """A bad example of an eval command"""
    await ctx.send(eval(code))

Look at how this example is done ^

vocal snow
sick birch
#

You pass in your check function into @commands.check() without calling it, discord.py will call it for you and provide ctx as well

glossy ocean
sick birch
#

You're 90% of the way there, you just need to change your decorator to @commands.check(dev_check)

vocal snow
sick birch
#

Course it is

glossy ocean
sick birch
glossy ocean
#

im kinda dumb lowkey

sick birch
#

dev_check vs dev_check()

#

the first is a first-class function, the other is calling the function

#

you are only passing in the function, not calling it

vocal snow
slate swan
#
@m.command()
@commands.check(dev_check)
async def uwu(ctx):
     pass```
sick birch
#

^ yep a more full version

slate swan
#

Oh God

sick birch
#

Is dev_check inside of a cog?

#

That would make sense

#

You'd want to import it in that case

slate swan
#

filename.dev_check

glossy ocean
sick birch
#

Can we see the import?

vocal snow
sick birch
#

That's not dev_check is it

#

Unless dev_check is a method of class check

#

Right, but you're not importing it here

glossy ocean
vocal snow
#

Correct

glossy ocean
slate swan
#

Can you for the last time, show us your dev_check function?

#

A full screen ss

#

And the filename?

glossy ocean
sick birch
#

check.py:

async def dev_check(ctx):
  ...

file2.py:

from check import dev_check

@commands.check(dev_check)
@commands.command()
async def someCommand(...):
  ...
vocal snow
pliant gulch
#

Check functions can be coroutines now?

#

:thonk:

sick birch
#

seems as if so

slate swan
#
'''USE THE CHECK FUNC'''
import check as ch

@m.command()
@commands.check(ch.dev_check)
async def uwu(ctx): pass```
glossy ocean
sick birch
#

To be able to call it that way, you need to do something even more complicated:

def is_owner():
    async def predicate(ctx):
        return ctx.author.id == 316026178463072268
    return commands.check(predicate)

@bot.command(name='eval')
@is_owner()
async def _eval(ctx, *, code):
    """A bad example of an eval command"""
    await ctx.send(eval(code))
vocal snow
#

!paste

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 floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

slate swan
#

Idk whats hard in understanding what Robin has been telling from the past 10 minutes

sick birch
#

Something more relevant to you:

def dev_check():
    async def predicate(ctx):
        # do a check here
    return commands.check(predicate)

@bot.command()
@dev_check()
async def someCommand(ctx):
    # command here
slate swan
sick birch
#

You have both options available to you

#

You pick which one you prefer, @commands.check(dev_check) or @dev_check()

glossy ocean
#

@vocal snow

sick birch
#

That's not necessarily an error

#

The check returned false

#

Your ID?

#

Oh you need to return true/false not pass

#

if message author is in dev list, return true, if not, return false

vocal snow
sick birch
#

alternatively, return if message author in dev list

pliant gulch
#

.udevs 😳

slate swan
#

This is a bad implementation of music commands in the first place, also, ytdl is against the yt tos

glossy ocean
vocal snow
slate swan
sick birch