#discord-bots

1 messages · Page 152 of 1

naive briar
unkempt canyonBOT
#

property me```
Similar to [`Client.user`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.user "discord.Client.user") except an instance of [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member"). This is essentially used to get the member version of yourself.
naive briar
#

!d discord.Member.guild_permissions

unkempt canyonBOT
#

property guild_permissions```
Returns the member’s guild permissions.

This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use [`abc.GuildChannel.permissions_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel.permissions_for "discord.abc.GuildChannel.permissions_for").

This does take into consideration guild ownership, the administrator implication, and whether the member is timed out.

Changed in version 2.0: Member timeouts are taken into consideration.
weary copper
#

would that work for determining the bot's permissions? or just other users?

#

the main reason I'm asking is because i keep getting a 403 forbidden error when I try to upload an emoji using create_custom_emoji, despite the fact I have given my bot manage_emoji permissions, and even Admin

naive briar
limpid hemlock
#

Can someone really Experienced in writing discord Bots DM me ? 😋🙏

weary copper
naive briar
#

You get the member object representing the bot from a guild by using guild.me, then use guild_permissions to get the permissions it has in the guild, then check if you have what you need

slate swan
weary copper
naive briar
#

Show your code

weary copper
#

sec, will get rid of the irrelevant stuff

#
from discord.ext import commands, tasks
import discord

description = "Test"
command_prefix = "!"
bot = commands.Bot(command_prefix=command_prefix, description=description, help_command=None, intents=discord.Intents.all())

@bot.event
async def on_ready(): # confirms that the bot is online
    print("We have logged in as {0.user}".format(bot))
    member_object = discord.Guild.me
    print(member_object.guild_permissions)```
#

that's just a part of it

naive briar
#

Ok

weary copper
pure wadi
#

what's the best method of round timer to use for rounds in a game?

naive briar
slate swan
#

you can use discord.Button.disabled and set it to True when the button is clicked, but remember to update the view again afterwards

weary copper
naive briar
#

In Python, of course

weary copper
#

yeah, they'd be like an instance of an object that inherit attributes and methods from a class, right?

#
class MyClass:
  val = 1

an_instance = MyClass()
an_instance.val # = 1```
right?
naive briar
#

Yeah

#

So you have to get an instance of your target guild

#

Like from context or interaction or something

weary copper
#

ahhh

#

is ctx.Guild a thing?

#

because it only lets me do lowercase guild

slate swan
#

!d discord.Guild

unkempt canyonBOT
#

class discord.Guild```
Represents a Discord guild.

This is referred to as a “server” in the official Discord UI.

x == y Checks if two guilds are equal.

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

hash(x) Returns the guild’s hash.

str(x) Returns the guild’s name.
slate swan
#

💀

quaint epoch
#

It will only affect the instantiated obj

weary copper
#

ah I still have no idea lol
i am doing ctx.guild and ctx.guild.id to get details of the server I'm in, but have no idea how to make the leap towards making a Guild instance object

shrewd apex
glad cradle
#

hi (i'm using disnake), is there the possibility to define a before_slash_command_invoke in a Bot subclass? something similar to events defined on Bot subclass

class MyBot(commands.Bot):
  def __init__(...):
    ...
  
  async def on_ready(...):
    ...
naive briar
shrewd apex
glad cradle
#

fuck decorators, i don't need them

weary copper
naive briar
#

What's the problem exactly

bright latch
#

changed it again above so the bot makes the text file somehow instead of as above

#

He should sort it as it was the case in the old code

naive briar
#

What does that mean

bright latch
naive briar
#

Why is the fp.seek in the for loop

#

You keep seeking to the begining every time it loops

bright latch
#

Isn't that the way it's supposed to be?

naive briar
#

No

bright latch
#

so like this

#
        with io.BytesIO() as fp:
            async for msg in interaction.channel.history(limit=None, oldest_first=True):
                fp.write(f"{msg.author.display_name} - {msg.clean_content}".encode())
            fp.seek(0)
            file = discord.File(fp, filename="ticket.txt")```
naive briar
#

Bruh

bright latch
#

Thanks it works

cerulean folio
#

hi guys, how do u make slash commands with dpy?

naive briar
#

Third pin

slate swan
#

The command help is already an existing command or alias.

#
async def help(ctx):
        embed = discord.Embed(color=000)
        embed.set_thumbnail(
            url=
            'MY LINK'
        )
        embed.add_field(name='Help', value=f'`?help`', inline=True)

        embed.add_field(name='Help Moderation',
                        value=f'`?help_mod`',
                        inline=True)

        embed.add_field(name='Help Music',
                        value=f'`?help_music`',
                        inline=True)

        embed.add_field(name='Help General',
                        value=f'`?help_general`',
                        inline=True)

        await ctx.send(embed=embed)```
#
async def help_music(ctx):
        embed = discord.Embed(color=000)
        embed.set_thumbnail(
            url=
            'MY LINK'
        )
        embed.add_field(name='Help Music', value=f'`?help_music`', inline=True)

        embed.add_field(name='Play',
                        value=f'`?play YOUTUBE_LINK`',
                        inline=True)

        embed.add_field(name='Pause',
                        value=f'`?pause`',
                        inline=True)

        embed.add_field(name='Resume',
                        value=f'`?resume`',
                        inline=True)

        embed.add_field(name='Stop',
                        value=f'`?stop`',
                        inline=True)

@bot.command()
async def help_general(ctx):
        embed = discord.Embed(color=000)
        embed.set_thumbnail(
            url=
            'MY LINK'
        )
        embed.add_field(name='Help General', value=f'`?help_general`', inline=True)

        embed.add_field(name='Membercount',
                        value=f'`?membercount / ?mc`',
                        inline=True)

        embed.add_field(name='Meme',
                        value=f'`?meme`',
                        inline=True)```
#

these are the only things with help.. and if i change their names same thing

pure wadi
#

so like if you change help to anything else you get the same conflict error?

slate swan
#

yup

#

and

#

now i have only 1 help command

#

and still that error

rare echo
#

default help command overlapping o.O?

#

presuming there’s nothing else in the code we can’t see

pure wadi
#

i thought so too but they're saying any name they give it throw the error

#

right?

slate swan
#

yup

#
async def help(ctx):
        embed = discord.Embed(color=000)
        embed.set_thumbnail(
            url=
            'MY LINK'
        )

        embed.add_field(name='Ban',
                        value=f'`?ban @USER`',
                        inline=True)
        embed.add_field(name='Unban',
                        value=f'`?unban USER#TAG`',
                        inline=True)
        embed.add_field(name='Kick',
                        value=f'`?kick @USER`',
                        inline=True)
        embed.add_field(name='Purge/Clear',
                        value=f'`?purge NUMBER / ?clear NUMBER`',
                        inline=True)
        embed.add_field(name='Mute',
                        value=f'`?mute @USER`',
                        inline=True)
        embed.add_field(name='Unmute',
                        value=f'`?unmute @USER`',
                        inline=True)
        embed.add_field(name='Membercount',
                        value=f'`?membercount / ?mc`',
                        inline=True)

        embed.add_field(name='Meme',
                        value=f'`?meme`',
                        inline=True)

        embed.add_field(name='Play',
                        value=f'`?play YOUTUBE_LINK`',
                        inline=True)

        embed.add_field(name='Pause',
                        value=f'`?pause`',
                        inline=True)

        embed.add_field(name='Resume',
                        value=f'`?resume`',
                        inline=True)

        embed.add_field(name='Stop',
                        value=f'`?stop`',
                        inline=True)
        await ctx.send(embed=embed)```
#

this is the only thing with help now

#

if i search in my code help this is the only thing

pure wadi
#

you def cant have this "async def help(ctx)"

slate swan
#

why not

pure wadi
#

help is already an internal keyword

slate swan
#

oh..

pure wadi
#

what command prefix are you using?

slate swan
#

than what should i put

rare echo
pure wadi
#

"halp"

slate swan
#

?

#

this isnt a question.. its the prefix xd

pure wadi
#

like in one of my games it's "/game help"

rare echo
#

pls dont actually do that

pure wadi
#

lol

slate swan
#

hmm

rare echo
slate swan
#

should i put async def mod_help(ctx)

rare echo
#

that works

pure wadi
#

the command you're registering is server wide, so the prefix command is unique to you

slate swan
#

ok bro tysm

#
async def setup(ctx: discord.Interaction):
  member = ctx.author
#

how do I get the author of an interaction command?

#
Traceback (most recent call last):
  File "/home/runner/advertising-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 862, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "main.py", line 79, in setup
    member = ctx.author
AttributeError: 'Interaction' object has no attribute 'author'
rare echo
#

user

slate swan
#

ok

#
async def ihelp(ctx):
        embed = discord.Embed(color=000)
        embed.set_thumbnail(
            url=
            'link'
        )
        embed.add_field(name='Help Moderation',
                        value=f'`?mod_help`',
                        inline=True)

        embed.add_field(name='Help Music',
                        value=f'`?music_help`',
                        inline=True)

        embed.add_field(name='Help General',
                        value=f'`?general_help`',
                        inline=True)

        await ctx.send(embed=embed)``` bro it dosent send the messgae 😭
#

but no error

short pulsar
slate swan
#

like

#

where? in the last line of help

short pulsar
#

No

slate swan
#

where?

short pulsar
#

Under this bot = Bot(
command_prefix="r!", # r! will be our prefix
case_insensitive=True # e.g. r!help is the same as r!HELP or r!hElP
)

slate swan
#

ooooh

short pulsar
#

Or like that

slate swan
#

thx

#
bot = commands.Bot(command_prefix="?", intents=intents)
bot.remove_command('help')``` like this @short pulsar ? i dont understand.. im tired sry 😭
short pulsar
#

Yuh

slate swan
#

dosent work

short pulsar
#

Under that

slate swan
#

dosent work 😭

short pulsar
#

No

#

You did it wrong

slate swan
#

oh

wind creek
#

bro I do not know

short pulsar
#

bot = commands.Bot(command_prefix=“?”, intents=discord.Intents.all()) bot.remove_command(‘help’)

#

Out of the bot = stuff

dull moon
#

do member.edit(roles=[]) remove those roles ?

wind creek
#

me ne it her

pliant gulch
dull moon
#

for me it doesnt 🙂

pliant gulch
#

Any error? Are you awaiting it?, etc

dull moon
#

no errors it just skipping it

#

oh i pass an empty list sorry

#

my bad

#

cuz of that

#
old_roles = []
    for role in member.guild.get_member(member.id).roles :
        if role.name == "@everyone" :
            pass
        else:
            old_roles.append(role)
        print(old_roles)
#

it prints []

slate swan
#
bot = commands.Bot(command_prefix="?", intents=intents)
bot.remove_command('help')``` its out the bot =
short pulsar
#

Hm

dull moon
#

use return

#

and when you call the def make it into a var

short pulsar
slate swan
#

wdym

dull moon
#

like x = def()
x will be the return

slate swan
#

so

bot = commands.Bot(command_prefix="?")
bot.remove_command('help')```
slate swan
#

like this?

slate swan
#

if this is the code.. still dosent work

#

Intent dosent exist?

#

andrew

dull moon
#

show me the code

glad cradle
#

from your_file import points should work

short pulsar
dull moon
#

oh thats so complicated

slate swan
#

bro now nothing works..

sick birch
#

Don't use globals. Rather, tie your points to your bot's variable

#

I believe you should have access to your bot from an interaction

glad cradle
#

ok

glad cradle
sick birch
#

You don't "transfer" it, you just bind it to your bot instance

glad cradle
#

you need to do bot.my_variable = points

slate swan
#

bro after i changed everything that u said it didnt work

glad cradle
#

then in your slash command you'll access the variable with self.bot.my_variable

slate swan
#

now i put everything back and still dosent work..

#

@short pulsar

glad cradle
slate swan
#

like nothing works not even a old command

short pulsar
#
bot = commands.Bot(command_prefix="?", intents=discord.Intents.all())

bot.remove_command('help')
#

use that

slate swan
#

dosent work

short pulsar
#

.

#

yes it does

slate swan
dull moon
#

why member.edit() doesnt remove roles

old_roles = []
    for role in member.guild.get_member(member.id).roles :
        if role.name == "@everyone" :
            pass
        else:
            old_roles.append(role)
    print(old_roles)
    await member.edit(roles=old_roles)
    print(member.guild.get_member(member.id).roles)

result :

[<Role id=835209959981187092 name="Some Fucken Io Games that doesn't work">, <Role id=835207964250996757 name='YouTube'>]
[<Role id=835188520359559188 name='@everyone'>, <Role id=835209959981187092 name="Some Fucken Io Games that doesn't work">, <Role id=835207964250996757 name='YouTube'>]

roles didnt changed

short pulsar
#
bot = commands.Bot(command_prefix="?", intents=discord.Intents.all(), case_insensitive=True)

bot.remove_command('help')
#

this is my personal code

#

try using client

slate swan
#

dosent work

short pulsar
#

...

wind creek
#

...

glad cradle
#

what error are you getting

#

could you share the code of the cog as well?

#

you're inside a view from what I can see

#

the error doesn't originated from these lines

#

if it's too long use !paste

#

!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.

glad cradle
#

btw if I'm not mistaken you can access your variable with interaction.client.my_variable only if you're inside the select menu callback

slate swan
#

how to provide choice options with slash command?

#

finally automatic entry

glad cradle
#

!d discord.Interaction.client

unkempt canyonBOT
#

property client```
The client that is handling this interaction.

Note that [`AutoShardedClient`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AutoShardedClient "discord.AutoShardedClient"), [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot"), and [`AutoShardedBot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.AutoShardedBot "discord.ext.commands.AutoShardedBot") are all subclasses of client.
glad cradle
#

what library are you using

slate swan
errant pecan
#

@glad cradle he doesn't like bot and client

glad cradle
errant pecan
rugged onyx
#

hi is there anyway here for me to pay someone to make a bot for me? i'm not sure if that's allowed on this server

glad cradle
#

the docs that I sent was referring to discord.py latest version, idk what you're doing in your code but what I said should work

unkempt canyonBOT
#

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

rugged onyx
#

ah i see okay thanks for letting me know

lone stump
#

could anyone help me create this discord bot 😄

$ python
> import discord
from discord.ext import commands
 client = commands.Bot(command_prefix = '!', intents=discord.Intents.all())

 @client.event
 async def on_message(message):
     if message.author == client.user:
         return

     if message.content.startswith('!search'):
         query = message.content[7:]
         if not query:
             await message.channel.send('Please provide a search query after the !search command.')
             return

         results = search_stanford_encyclopedia(query)

         # Send the results back to the user
         await message.channel.send(results)

>>>
> def search_stanford_encyclopedia(query):
>      # Use Selenium to search the Stanford Encyclopedia of Philosophy
> driver = webdriver.Chrome()
>      driver.get('https://plato.stanford.edu/')
>         search_box = driver.find_element_by_id('search')
>         search_box.send_keys(query)
>         search_box.submit()
>         results = driver.find_elements_by_class_name('result')
>         results = [result.text for result in results]
>         driver.close()
>         return results
>         
rare echo
#

there’s packages so you don’t have to use selenium o.O

#

and you have a prefix so instead of using on_message make an actual command

#

what’s wrong with dpy?

glad cradle
#

try to print the type of the interaction and send the output here

lone stump
rare echo
#

not really?

unkempt canyonBOT
#

Hey @lone stump! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discord.com/developers/applications

Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!

rare echo
lone stump
#
import discord
from discord.ext import commands
import requests
from bs4 import BeautifulSoup

client = commands.Bot(command_prefix = '!')

@client.command()
async def search(ctx, *, query):
    results = search_stanford_encyclopedia(query)

    # Send the results back to the user
    await ctx.send(results)

def search_stanford_encyclopedia(query):
    # Use requests and BeautifulSoup to search the Stanford Encyclopedia of Philosophy
    search_url = f'https://plato.stanford.edu/search/searcher.py?query={query}'
    search_page = requests.get(search_url)
    soup = BeautifulSoup(search_page.content, 'html.parser')

    # Get the search results and create a string with the title and URL for each result
    results = []
    for result in soup.find_all('h3', class_='title'):
        title = result.text
        url = result.find('a')['href']
        results.append(f'{title}: {url}')

    return '\n'.join(results)

client.run('<bot token>')```
#

will this work?

rare echo
#

this sounds like a very personal opinion, docs are fine

rare echo
glad cradle
#

Well it depends where you putted the print statement 😭

lone stump
#

i'm trying to get chatgpt to write it for me

#

stanford because i am using it as my philosophy bot for my server

rare echo
#

with a general python knowledge the docs are quite easy to read imo, you just need a overview of what you are doing

rare echo
slate swan
lone stump
#

stanford doesn't seem to have an api

rare echo
glad cradle
#

actually the docs of Discord.py and other forks are done quite well, very often using other modules (even quite famous) I have to look directly at the source code 😭

rare echo
lone stump
#

why does this issue occur

errant pecan
lethal elbow
#

You are missing intents

#

Also consider type hint your code. OwO

lone stump
#
client = commands.Bot(command_prefix='!', 
intents=discord.Intents.all())
lethal elbow
#

lone stump
#

says requirement already satisfied

#

@errant pecan

#
(base) ~@MacBook-Air-som-tillhor-… ~ % pip install discord.py

zsh: /usr/local/bin/pip: bad interpreter: /System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python: no such file or directory
Requirement already satisfied: discord.py in ./opt/anaconda3/lib/python3.9/site-packages (2.1.0)
Requirement already satisfied: aiohttp<4,>=3.7.4 in ./opt/anaconda3/lib/python3.9/site-packages (from discord.py) (3.8.3)
Requirement already satisfied: attrs>=17.3.0 in ./opt/anaconda3/lib/python3.9/site-packages (from aiohttp<4,>=3.7.4->discord.py) (21.2.0)
Requirement already satisfied: aiosignal>=1.1.2 in ./opt/anaconda3/lib/python3.9/site-packages (from aiohttp<4,>=3.7.4->discord.py) (1.3.1)
Requirement already satisfied: async-timeout<5.0,>=4.0.0a3 in ./opt/anaconda3/lib/python3.9/site-packages (from aiohttp<4,>=3.7.4->discord.py) (4.0.2)
Requirement already satisfied: yarl<2.0,>=1.0 in ./opt/anaconda3/lib/python3.9/site-packages (from aiohttp<4,>=3.7.4->discord.py) (1.8.2)
Requirement already satisfied: charset-normalizer<3.0,>=2.0 in ./opt/anaconda3/lib/python3.9/site-packages (from aiohttp<4,>=3.7.4->discord.py) (2.0.4)
#

etc

glad cradle
lone stump
#

~ % python --version
Python 3.9.7

glad cradle
#

I didn't ask which version you're using

lone stump
#

~ % ls /usr/local/bin | grep python

python3
python3-config
python3-intel64
python3.10
python3.10-config
python3.10-intel64
python3.9
python3.9-config
python3.9-intel64

#

is this what you were looking for

#

@glad cradle

lethal elbow
#

Python 2.7???

lone stump
#

it's a list of all the Python executables that are installed on the system, along with their version numbers

lone stump
lethal elbow
glad cradle
lone stump
#

okay

glad cradle
#

probably you're installing d.py for a python interpreter thay you're not using in vscode

lone stump
near wolf
#

my oauth2 code is like this```py
def getallmsg(self):
url = f'{API_ENDPOINT}/channels/1035894512117104790/messages?limit=100'
headers = {
'Authorization':f'Bearer {self.token}'
}
print(headers)
res = requests.get(url,headers=headers)
json:list = res.json()
print(json)
for i in json:
print(i)

lone stump
#
~ % /usr/local/bin/python3.9 "/Users/…/Desktop/Phil
osophy bot.py"
2022-12-10 00:04:42 INFO     discord.client logging in using static token
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/aiohttp/connector.py", line 980, in _wrap_create_connection
    return await self._loop.create_connection(*args, **kwargs)  # type: ignore[return-value]  # noqa
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 1081, in create_connection
    transport, protocol = await self._create_connection_transport(
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 1111, in _create_connection_transport
    await waiter
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/sslproto.py", line 528, in data_received
    ssldata, appdata = self._sslpipe.feed_ssldata(data)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/sslproto.py", line 188, in feed_ssldata
    self._sslobj.do_handshake()
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/ssl.py", line 944, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1129)

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

Traceback (most recent call last):
  File "/Users/~/Desktop/Philosophy bot.py", line 37, in <module>
    client.run('<bot-token>')
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/client.py", line 828, in run
    asyncio.run(runner())
#
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 642, in run_until_complete
    return future.result()
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/client.py", line 817, in runner
    await self.start(token, reconnect=reconnect)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/client.py", line 745, in start
    await self.login(token)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/client.py", line 580, in login
    data = await self.http.static_login(token)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/http.py", line 801, in static_login
    data = await self.request(Route('GET', '/users/@me'))
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/http.py", line 624, in request
    async with self.__session.request(method, url, **kwargs) as response:
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/aiohttp/client.py", line 1141, in __aenter__
    self._resp = await self._coro
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/aiohttp/client.py", line 536, in _request
    conn = await self._connector.connect(
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/aiohttp/connector.py", line 540, in connect
    proto = await self._create_connection(req, traces, timeout)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/aiohttp/connector.py", line 901, in _create_connection
    _, proto = await self._create_direct_connection(req, traces, timeout)
#
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/aiohttp/connector.py", line 1206, in _create_direct_connection
    raise last_exc
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/aiohttp/connector.py", line 1175, in _create_direct_connection
    transp, proto = await self._wrap_create_connection(
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/aiohttp/connector.py", line 982, in _wrap_create_connection
    raise ClientConnectorCertificateError(req.connection_key, exc) from exc
aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1129)')]```
#

why do i get these errors…

near wolf
#

seems like its cuz something blocked the connection to discord.com

lone stump
#
import discord
from discord.ext import commands
import requests
from bs4 import BeautifulSoup
import aiohttp

client = commands.Bot(command_prefix='!', verify=False,
                      intents=discord.Intents.all())

async def start():
    # Create the aiohttp ClientSession object
    session = aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False))


@client.command()
async def search(ctx, *, query):
    results = search_stanford_encyclopedia(query)

    # Send the results back to the user
    await ctx.send(results)

def search_stanford_encyclopedia(query):
    # Use requests and BeautifulSoup to search the Stanford Encyclopedia of Philosophy
    search_url = f'https://plato.stanford.edu/search/searcher.py?query={query}'
    search_page = requests.get(search_url, verify=False)
    soup = BeautifulSoup(search_page.content, 'html.parser')

    # Get the search results and create a string with the title and URL for each result
    results = []
    for result in soup.find_all('h3', class_='title'):
        title = result.text
        url = result.find('a')['href']
        results.append(f'{title}: {url}')

    return '\n'.join(results)

client.run('<bot-token>')
#

here's what the code looks like

pallid mango
unkempt canyonBOT
pallid mango
#

!d discord.Guild.ban

unkempt canyonBOT
#

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

Bans a user from the guild.

The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.

You must have [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") to do this.
nocturne hamlet
#

Can someone tell my why py-cord is helpful please @nocturne hamlet on your answers

mighty yarrow
glad cradle
#

!d discord.TextChannel.create_thread

unkempt canyonBOT
#

await create_thread(*, name, message=None, auto_archive_duration=..., type=None, reason=None, invitable=True, slowmode_delay=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates a thread in this text channel.

To create a public thread, you must have [`create_public_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_public_threads "discord.Permissions.create_public_threads"). For a private thread, [`create_private_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_private_threads "discord.Permissions.create_private_threads") is needed instead.

New in version 2.0.
mighty pilot
#

i have my giveaway bot sleeping while the giveaway is being run. i started to make a manual command to end a giveaway but is there a way to stop the sleep timer? so it doesnt continue counting down and trigger the giveaway to end twice

fading marlin
#

make it a task

mighty pilot
#

i hate that that answer is the right way to do it. i guess i can take the whole second half of the command block and put it inside a task

fading marlin
#

not exactly @tasks.loop btw

#

!d asyncio.create_task

unkempt canyonBOT
#

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

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

An optional keyword-only *context* argument allows specifying a custom [`contextvars.Context`](https://docs.python.org/3/library/contextvars.html#contextvars.Context "contextvars.Context") for the *coro* to run in. The current context copy is created when no *context* is provided.

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

Note

[`asyncio.TaskGroup.create_task()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.TaskGroup.create_task "asyncio.TaskGroup.create_task") is a newer alternative that allows for convenient waiting for a group of related tasks.
mighty pilot
#

alright

#

i was definitely about to throw it inside a tasks.loop and just end the loop after the first execution

mighty pilot
# fading marlin !d asyncio.create_task

just want to make sure im reading this right - i create_task(sleep(x-time, name = sleeptask)) and itll work like a regular sleep but i now have the ability to cancel the task (sleep)

fading marlin
#

you'd usually have the task surround all of the events that you want to be able to cancel, but yeah. create_task accepts only coroutines too

#

you don't have to name the task either

mighty pilot
#

alright cool. thanks

mighty pilot
slate swan
#
          channel = await ctx.guild.create_voice_channel(name=f'Goal: {text}')
          await ctx.response.send_message(f"Goal has been set to {text}")
          channel = channel.id
          c = channel
        elif result is not None:
          await cursor.execute("UPDATE users SET goal = ? WHERE guild = ? AND goalchannel = ?", (text, ctx.guild.id, c,))
          await cursor.execute("SELECT goal FROM users WHERE guild = ? AND goalchannel = ?", (ctx.guild.id, c,))
          result = await cursor.fetchone()
          
          await ctx.response.send_message(f"Goal has been updated to {text}")
          await result[1].edit(name=f'Goal: {text}')
#
Traceback (most recent call last):
  File "/home/runner/advertising-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 862, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "main.py", line 118, in goal
    await result[1].edit(name=f'Goal: {text}')
IndexError: tuple index out of range

The above exception was the direct cause of the following exception:
slate swan
#

Try printing result or do
await result[1].edit()

#
  File "C:\Users\milos\OneDrive\Desktop\verification\main.py", line 17, in <module>
    from async_hcaptcha import AioHcaptcha
  File "C:\Users\milos\AppData\Local\Programs\Python\Python310\lib\site-packages\async_hcaptcha\__init__.py", line 1, in <module>      
    from .asynchcaptcha import AioHcaptcha
  File "C:\Users\milos\AppData\Local\Programs\Python\Python310\lib\site-packages\async_hcaptcha\asynchcaptcha.py", line 22, in <module>
    hcaptcha_challenger.logger.remove() # TODO: Redirect logs from loguru to logging or use loguru instead of logging
AttributeError: module 'hcaptcha_challenger' has no attribute 'logger'
PS C:\Users\milos\OneDrive\Desktop\verification> ```

https://docs.python.org/3/library/logging.html i tried reading this but it doesnt help
tacit storm
#

just finished fully implementing my caching stuff in my discord wrapper yay only took about 100 or so lines of code just for caching channels, guilds, and members

#

was way easier than i expected tbh specially since ive heard that caching was one of the hardest parts

slate swan
#

but i implement cache for each object seperately

tacit storm
#

ah lol

slate swan
#

maintaining it is even harder

#

its just a dictionary in the end

tacit storm
#

the most line demanding part of the whole cache handler was some adding shit

#

the logs on the terminal are for somerthing im testing for btw

#

trying to test to see if my reconnecting is working or not which takes up time grief

slate swan
#

Haven't made a guild object yes so no guild cache for me sadly

#

@shrewd apex bro push guild object when

tacit storm
#

okay that code is a bit outdated there

slate swan
#

thats a progress

tacit storm
shrewd apex
tacit storm
#

oh shit wait i didn't realize that was you sarth, whats good man

#

genuinely thought you were someone random LOL

slate swan
#

thanks to discord for making these many Channel types

tacit storm
slate swan
#

other than that im lively

tacit storm
#

tbh all my models are incredibly unfinished, the most 'finished' one is my member model and it doesn't even have all the data lol

slate swan
#

im also confused with my naming sense
i currently have hikari-tanjun styled function names on_listener/with_listener

#

im thinking if i should let it be that way or use simple names

tacit storm
#

oh okay good so embedding links work here thankfully

slate swan
tacit storm
#

fuck that smh smh

#

i dont know how to use the attrs lib tbh

#

never looked into it 💀

#

crazy how fast 45 seconds go by jesus

slate swan
tacit storm
#

only like once

slate swan
#

its exactly the same but faster with development

tacit storm
#

oh

#

sarth, by chance do you know how to fetch only a specific channel through the api?

slate swan
#

isn't there a get channel endpoint

tacit storm
#

only a get channels

#

oh wait nvm

#

i did not EVER see it, it disappeared on the docs for me lol but i see it now in the channel section

slate swan
#

i made someone ( ahem asher) write a class with all endpoints for me

shrewd apex
tacit storm
#

also sarth did you look at dms about the ratelimit stuff

slate swan
#

ohh no sorry lemme see

slate swan
tacit storm
#

i have zero clue what discord.py's ratelimiter looks like if im honest

#

i went into wharf raw aka i didnt look at any other api wrapper's source

#

everything has been pure trial and error lol

slate swan
#

thats nicee

tacit storm
#

dude tbh i have way more stars on wharf then i ever expected to have already lol

slate swan
#

i took some impl ideas from hikari
like using direct bitfields instead of properties for flags

slate swan
#

it shows used by 2 in dependencies

tacit storm
#

lmfao

slate swan
tacit storm
#

what

#

oh yeah

slate swan
#

LoC- lines of code

tacit storm
#

its github gloc

slate swan
#

are you trying to install ssl certificates?

#

open the python folder and click on install certificates thats all

rugged shadow
#

whoopsies best commit name yo

slate swan
#

use a ATTACHMENT type option

inland stream
#

!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.

slate swan
#

depends on the library you're using

glad cradle
slate swan
glad cradle
#

the bot functionalities are stupid

slate swan
#

for the codebase here's some things that can be fixed:

  • folder name slashCommands -> slash_commands
  • import orders in many places are random, ```py
    import builtin_module1
    import builtin_module2
    from builtin_module3 import ...

import installed_package
import installed_package2

import global_level_package

import local_files


- i think there's some lines exceeding 88/120 lines ( whatever max - lenght you follow ) you could use a string concenteration for them ( like this one: <https://github.com/Snipy7374/SnipyBot-CodeWithVincentServer/blob/c0430c5c0f788a791f40625ac2d8e9fcdb58bb53/slashCommands/roles_giver.py#L58)>
unkempt canyonBOT
#

slashCommands/roles_giver.py line 58

await interaction.response.send_message(f"{picked_role.mention} was succesfully added to your member profile (note also {newbie_role.mention} was added to give you the access to the server)", ephemeral=True)```
glad cradle
#

yeah ik, i need to adapt to PEP8, when i writed the basecode i was a noob

slate swan
unkempt canyonBOT
#

slashCommands/packages_searcher.py line 21

class Package:```
slate swan
#

instead of getting attrs from the dict youll be able to ```py
from dataclasses import dataclass
@dataclass(repr=True)
class Package:
name: str
url: str

Package("discord.py", "pypi.org/project/discord.py")

#

or atleast one for the complete cog

#

guys can anyone help me?

#

I havent coded in a long time and now my thingy doesnt work

#
import discord
import random
from discord.ext import commands

bot = commands.Bot(command_prefix="2?", intents=discord.Intents.all())


bot.command
async def towers(ctx):
  TowersList =(":coin: :coin: :bomb:", ":coin: :bomb: :coin:", ":bomb: :coin: :coin:")

  TowersEmbed = discord.Embed(title="Enjoy :cozysip:", description = {random.choice(TowersList)})
  await ctx.send(TowersEmbed)



my_secret = os.environ["Token"]
bot.run(my_secret)```
#

surely, this is what this channel is meant for.

vale wing
#

What kind of naming convention is this

slate swan
#

ohhh right

#

and the embed should be sent with embed kwarg

vale wing
#

I don't know any languages where variable names start from capital letter

slate swan
#

I forgot so many things lol

slate swan
#

OH RIGHT

slate swan
vale wing
#

No

#

It's IMakeMyOwnRules

vale wing
slate swan
#

f strings gone wrong

#

i just realised python's pep page is hosted on github pages lmaooo

slate swan
#

i was looking for pep69

glad cradle
slate swan
slate swan
#

i didnt get a notif from you

slate swan
#

They doesn't even give notification

vale wing
#

This is definitely IMakeMyOwnRules

slate swan
#

🗿

#

let var = "lol";

#

Idk js 🙂

#

var is a keyword in js lol

vale wing
slate swan
#

;-;

slate swan
#

its more fked up on mobile client

slate swan
vale wing
#

Mobile client used to be a giant f itself

slate swan
#

All knows 🤷

vale wing
#

It still is but not that giant

slate swan
#

Nah dawg after recent update

#

Mobile client is now like worst

#

For me altho

#

This update's before update used to fk my phone whenever i open a channel where is a embed with "gif"

toxic kayak
#

Hi everyone, I made a bot with python that runs, however I don't know how to let it run asynchronously (idk if that's that right word)

Basically, how do I host this bot without having to manually do it? Thank you!

slate swan
#

U want a host? Or smthing

#

Shit dude am bad at understanding 🤷

toxic kayak
#

ahhh this is like my first proper bot so i have no idea either 😭

slate swan
#

Here

#

If u need a host 🙂

toxic kayak
#

ahhh thank you!!1

vale wing
#

My PR recently got merged

#

Their markdown processor smokes smth

glad cradle
slate swan
glad cradle
slate swan
#

!pypi attrs

unkempt canyonBOT
slate swan
#

3.8+

#

same features

#

just gotta replace dataclasses.dataclass with attrs.define in the above example

#

!e ```py
import attrs

@attrs.define(kw_only=True, repr=True)
class Package:
url: str
name: str

data = {"name": "hehe", "url": "amogus.com"}

print(Package(**data))

unkempt canyonBOT
#

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

Package(url='amogus.com', name='hehe')
glad cradle
#

you're the second person that talks about attrs so ig i'll look into it

feral frost
#

how do i remove this cuz when i want to click tab this pops up and it annoying

slate swan
feral frost
slate swan
feral frost
#

you said github copilot right ?

slate swan
#

yes

feral frost
#

i dont even have that extension

feral frost
slate swan
#

might be tabnine or something

timid spade
#

you have to give a custom id to all options if you want to make a persistent drop down menu?

slate swan
#

yes

glad cradle
#

isn't the select menu to which the custom ID is set?

slate swan
#

all i remember is that all components with custom_id option should have it provided

glad cradle
#

yes but SelectOption isn't a component

slate swan
#

ye

timid spade
#

there is no custom id here

slate swan
#

you dont need it

glad cradle
#

!d discord.ui.Select

slate swan
#

just add a custom_id for the 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.
glad cradle
#

you set a custom id for the dropdown menu (aka select) not for the options

timid spade
glad cradle
timid spade
#

ok cool

#

persistent views for buttons and selections are almost same right?

regal cove
#

i need help. i tried to migrate an old bot using a normal prefix to "/" commands and for some reason the commands doesnt even show up. i get no error but it just doesnt work at all. Here is an example of a command:

rare echo
#

did you sync

#

or debug guild, if not it could take a while

regal cove
#
@tree.command(name = 'bal_unban', description='This will unban the user from the economy system') 
async def bal_unban(ctx,  member: discord.Member):
   with open("ban_data.json", "r") as openfile:
        ban_list = json.load(openfile)
   if ctx.message.author.id == (767636284083666971):
        amount = 1
        member_get = str(ctx.message.author.id)
        getter_get = str(member.id)
        getter_balance = int(ban_list.get(getter_get))
        
        if getter_balance == 1:
            if not member_get == getter_get:
              await ctx.channel.send(str(member) + " has been unbanned")
               
              new_getter_balance = getter_balance - amount

              print(getter_balance)
              ban_list[getter_get] = new_getter_balance

            else: await ctx.message.send("Dont try to unban yourself")
        else: await ctx.channel.send("This user is not banned")
   else: await ctx.channel.send("You're not allowed to perform this command")
   with open("ban_data.json", "w") as outfile:
     json.dump(ban_list, outfile)
#
class aclient(discord.Client):
    def __init__(self):
        super().__init__(intents = discord.Intents.default())
        self.synced = False #we use this so the bot doesn't sync commands more than once

client = aclient()
tree = app_commands.CommandTree(client)
upbeat otter
unkempt canyonBOT
#

Hey @thorny frost!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

thorny frost
rare echo
thorny frost
rare echo
#

are u using repl?

upbeat otter
#

nvm 💀

thorny frost
#

ok lemme explain u, i used discloud before, now the server was nuked and thus i was scared for my bot token to be stolen, so i switched to replit because i had no other choice

rare echo
#

yeah repl is causing your bot to get ratelimited

thorny frost
#

i new to repl

thorny frost
rare echo
#

too many requests to discord, extremely common on repl because its shared ip's

#

just host somewhere else

thorny frost
upbeat otter
rare echo
#

if you got card verification, use oracle cloud

#

otherwise check the pins, theres a message all about hosting a bot

thorny frost
#

i don't wanna pay no money

rare echo
#

oracle is free u just need card verification

#

or they have free plan rather

thorny frost
rare echo
#

you need to verify a card, but it wont charge

regal cove
thorny frost
regal cove
#

why does one work and another dont when they have the same code (not the same commands)

rare echo
thorny frost
#

it's patched nwo

upbeat otter
#

just use a legit card ¯_(ツ)_/¯

thorny frost
upbeat otter
thorny frost
#

16

upbeat otter
regal cove
rare echo
thorny frost
thorny frost
rare echo
#

yeah

thorny frost
#

🛑 Note : Access our code in our discord server : - dsc.gg/logistack

🌐 Links : -
Discord : https://dsc.gg/logistack

Host a Discord Bot 24/7 for free forever using oracle cloud free tier which offers 4 OCPU cores and 24GB of RAM:

ℹ️ Install node commands:
| curl -fsSL https://rpm.nodesource.com/setup_16.x | sudo bash -
| sudo yum install -y nod...

▶ Play video
#

is this legit?

regal cove
# upbeat otter which library?
import discord
from discord.ext import commands
import aiosqlite
import random
from discord import app_commands 
import os
from keep_alive import keep_alive
import asyncio
from random import randint

class aclient(discord.Client):
    def __init__(self):
        super().__init__(intents = discord.Intents.default())
        self.synced = False #we use this so the bot doesn't sync commands more than once
#

thats everything i've downloaded just to make sure i dont miss any information you might need

upbeat otter
regal cove
#
class aclient(discord.Client):
    def __init__(self):
        super().__init__(intents = discord.Intents.default())
        self.synced = False #we use this so the bot doesn't sync commands more than once

client = aclient()
tree = app_commands.CommandTree(client)
rare echo
upbeat otter
slate swan
upbeat otter
slate swan
#

oracle doesnt allow fake ccs

slate swan
upbeat otter
#

lmao

regal cove
#

i copied my code from one but forgot to copy the on_ready function which is where i synced the commands

upbeat otter
#

don't sync inside on_ready smh

regal cove
#

well thank you for helping me find this error bro i really appriciate it

#

why?

upbeat otter
timid spade
#

persistent views for buttons and selections are almost same right?

slate swan
#

Otters 🛐

regal cove
#

so that should be fine

upbeat otter
timid spade
slate swan
upbeat otter
timid spade
#

fr it is

slate swan
#

guys how do I get URL of my bot in replit? I need it for uptimerobot

#

you run a webserver using flask and get the url from the side window

slate swan
#

idk, i neither use replit, nor suggest it
you can google

upbeat otter
#

🛐

upbeat otter
slate swan
#

back

slate swan
slate swan
slate swan
slate swan
# slate swan I tried to google but nothing came up

https://docs.replit.com/tutorials/build-basic-discord-bot-python
first result for "replit python discord bot"

In this tutorial, we'll use Replit and Python to build a Discord chatbot. If you're reading this tutorial, you probably have at least heard of Discord and likely have an existing account. If not, Discord is a VoIP and chat application that is designed to replace Skype for gamers. The bot we create in this tutorial will be able to join a Discord ...

#

scroll down they tell you what to do

slate swan
#

I copy pasted this

app = Flask('Pro Predictor')

@app.route('/')
def home():
return "I'm alive"

def run():
app.run(host='0.0.0.0',port=8080)

def keep_alive():
t = Thread(target=run)
t.start()

#

but it still didn't work

#

🤷‍♂️ you need to read everything they ask you to do

#

ok now it worked

#

Thanks a lot.

slender stirrup
#

Is there any way to get audit log like event

slate swan
#

@slate swan

#

U there

#

yes

#

how to install a package in windows vs terminal 🤷

#

pip install package-name

slate swan
#

For a guy

#

python -m pip

rare echo
#

python -

#

speedy ass

slate swan
#

or py -m pip

#

ok

#

py -m pip install shit?

#

yes

#

🤷

#

Ok

#

!pip pycountry

unkempt canyonBOT
#

ISO country, subdivision, language, currency and script definitions and their translations

slate swan
timid spade
#

it should be like this eh?

#

or this can work too?

slate swan
timid spade
slate swan
#

custom_id="lol"

#

Do it

timid spade
#

its saying custom id and options are required
and i have given them, still saying they are required

naive briar
#

What

slate swan
naive briar
#

Are you sure that your customid variable is not none

slate swan
#

Autograph pls

naive briar
#

Or options even

timid spade
#

it was a string wth..

#

but this one is list

timid spade
naive briar
#

It's a list doesn't mean it always has any elements in it

timid spade
naive briar
#

Print both the custom id and options

#

See if they're none

timid spade
slate swan
#

don't use "" as custom id lol

timid spade
#

i added custom id as an argument in command

#

i changed nothing and the error is this now 🤡

vale wing
#

Clown emoji 💀

timid spade
#

🤡 .

vale wing
vale wing
#

Where bro

timid spade
#

except the options thing is everything good?

vale wing
#

Ya see __init__? Ya see its signature?

#

I only see self

#

No timeout

timid spade
#

ouch

late ruin
#
  '.format(client))```
what is wrong?
timid spade
vale wing
#

You shouldn't have added it

#

You should've removed it from the place where you instantiate the view

#

As it's extra argument

#
class YourView(View):
    def __init__(self):
        super().__init__(timeout=None)


view = YourView()```
timid spade
vale wing
#

!f-strings

unkempt canyonBOT
#

Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.

>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."

Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.

vale wing
late ruin
timid spade
late ruin
#

what is wront now 😭 ?

vale wing
#

Discord is now 2 gb on mobile wtf

timid spade
#

@vale wing are you free rn? I want help with making persistent views for select options
can you help?

vale wing
late ruin
#

Learn how to code a Discord bot using Python and host it for free in the cloud using Repl.it.
🚨Note: At 16:43, Replit now has a new method for environment variables. Check the docs: https://docs.replit.com/programming-ide/storing-sensitive-information-environment-variables

Along the way, you will learn to use Repl.it's built-in database and cr...

▶ Play video
vale wing
#

AHAH

#

The fcc tutorial

timid spade
vale wing
#

Honestly I don't even know what modern tutorial to recommend

#

!resources maybe look there

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.

timid spade
#

just tell me is it as it should be? it will help

vale wing
#

I just got home from 1 week work trip and jetbrains new design got me like

late ruin
#

crazy shit

vale wing
timid spade
vale wing
#

Yeah live share extension

#

Or smth

late ruin
#

do you can recomend tutorial not outdated with slash commands?

pure dirge
vale wing
#

Vise versa

slate swan
#

anyoen help

#

it shows this error

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'coroutine' object is not callable

naive briar
#

Await it

slate swan
#

I literally did this

await ctx.send("We generated the 3 safest mines. :cozysip: ")(random.choice(MinesList))

naive briar
#

!async-await

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.

slate swan
#

await ctx.send("We generated the 3 safest mines.")(random.choice(MinesList))

naive briar
slate swan
naive briar
#

Then use f-string to put it in the string before sending it

slate swan
#

how? it used to work but now it doesn't

#

I havent coded in a year

naive briar
#

!f-string

unkempt canyonBOT
#

Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.

>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."

Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.

slate swan
#

no like how do I fix this??

#

await ctx.send("We generated the 3 safest mines. :cozysip: ")(f"random.choice(MinesList)")

naive briar
#

Remove what ever you're trying to do after the ctx.send

slate swan
#

like this or what?

naive briar
#

Do you know how functions work

slate swan
#

kinda, I haven't coded for a year so its hard

naive briar
#

!e

import asyncio
from random import randrange

async def afunc(n):
    print(n)

async def main():
    await afunc(f"Random num: {randrange(1, 11)}")

    await afunc(f"Random num: ")(randrange(1, 11))

asyncio.run(main())
unkempt canyonBOT
#

@naive briar :x: Your 3.11 eval job has completed with return code 1.

001 | Random num: 9
002 | <string>:10: RuntimeWarning: coroutine 'afunc' was never awaited
003 | RuntimeWarning: Enable tracemalloc to get the object allocation traceback
004 | Traceback (most recent call last):
005 |   File "<string>", line 12, in <module>
006 |   File "/usr/local/lib/python3.11/asyncio/runners.py", line 190, in run
007 |     return runner.run(main)
008 |            ^^^^^^^^^^^^^^^^
009 |   File "/usr/local/lib/python3.11/asyncio/runners.py", line 118, in run
010 |     return self._loop.run_until_complete(task)
011 |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/usacidemog.txt?noredirect

slate swan
#

just tell me what to do to fix this

#

await ctx.send("We generated the 3 safest mines. :cozysip: ")(random.choice(MinesList))

#

what do I change in here?

#

What u want to do?

naive briar
#

Remove whatever you're trying to do after the ctx.send

slate swan
naive briar
#

And is the current one works?

slate swan
#

Ik what u r trying to do

slate swan
#

U r trying to take random 3 str from a list obj

#

And send it

slate swan
#

its like a link that has 3 things in it

slate swan
naive briar
#

Ok

slate swan
#

Its ez

naive briar
#

Someone explain to him

slate swan
#

xd

naive briar
#

I'm out

slate swan
#

how do I paste?

#

!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
#

await ctx.send(f"some msg {random.choice(MineList)}")

#

🤷 ez as dat

#

oh thanks

#

Yo bro

#

Ur list isn't even correct 🤷

#

MineList=[]
change () to []

#

ik I just noticed lol

#

xd

naive briar
#

It's for creating a tuple

slate swan
slate swan
#

He is trying to take something from ah whatever

primal token
slate swan
#

I am out too 🗿

primal token
#

🤔

slate swan
#

globals().get("ah whatever", TypeError("skill issue"))

slate swan
#

I have aah coding issues

#

Just because of this shit exam

#

go study

slate swan
#
exam = 2
if exam == 0:
  spooky.release('freedom')```
#

That will never happen according to this coding 🗿

grizzled kestrel
#

my exams finished yesterday

#

freedom at last

slate swan
#

i don't have any exams anytime soon

upbeat otter
slate swan
#

thats 1 month

upbeat otter
#

"soon"

#

mine start from wednesday 😔

slate swan
# upbeat otter "soon"

not preparing for Jan session, coaching teachers straightforward said they'll complete the syllabus in mid-feb lol

upbeat otter
#

💀

slate swan
slate swan
upbeat otter
slate swan
#

i forgor to watch spyxfam again

slate swan
slate swan
#

xd my net

timid spade
#

is it the right way to make the persistent view?

slate swan
#

Why u passing timeout in __init__

timid spade
slate swan
timid spade
#

i just have to solve the options problem then

slate swan
#

Try printing option after executing command

#

I mean after interaction

timid spade
cloud dawn
#

<@&831776746206265384>

lost marten
#

Ah yes the invisible profile picture

#

What a genius troll /s

timid spade
#

is replit down?

regal cove
#

why can i not access ctx.message.author.id on this script

@tree.command(name = 'bal', description='This command will tell you your or someone elses balance') 
async def show_balance(ctx, member: discord.Member = None):
  db = client.database_connection
  cursor = await db.cursor()
  USER_ID = ctx.message.author.id
  USER_NAME = str(ctx.message.author)
#

i get this error when i try to use the command

  File "/home/runner/modern-economy-bot-2/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/runner/modern-economy-bot-2/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/runner/modern-economy-bot-2/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 880, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'bal' raised an exception: AttributeError: 'NoneType' object has no attribute 'author'
sick birch
#

The thing is so bad you can't tell the difference

naive briar
#

Why is there a ctx in a slash command callback

cloud dawn
#

damn

regal cove
# cloud dawn `ctx.author.id`

i get this error when i do that

  File "/home/runner/modern-economy-bot-2/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/runner/modern-economy-bot-2/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/runner/modern-economy-bot-2/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 880, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'bal' raised an exception: AttributeError: 'Interaction' object has no attribute 'author'```
glad cradle
#
2022-12-10 17:47:21.890 | INFO     | _logging:log_message:43 - :SnipyBot.my_after_slash_command_invoke: - Snipy#7374 - 710570210159099984 | CodeWithVincent - 920882891024629790 | Command search was executed in 0.616953s
2022-12-10 17:47:22.928 | INFO     | _logging:log_message:43 - :SnipyBot.my_after_slash_command_invoke: - Snipy#7374 - 710570210159099984 | CodeWithVincent - 920882891024629790 | Command search was executed in 1.654488s

when i run a slash subcommand after_slash_command_invoke gets called twice, i can understand the motivation behind this, but why if i try to print the name of the InvokableSlashCommand i get the same name? (i'm using disnake)

naive briar
#

!d discord.Interaction.user

unkempt canyonBOT
late ruin
#

how to fix that error?

cloud dawn
#

What error?

late ruin
#

@cloud dawn

cloud dawn
#

!d discord.Asset.url

unkempt canyonBOT
cloud dawn
#

!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 does not have a traditional 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").
late ruin
#

so change ctx.message.author.avatar.url to discord.User.avatar?

cloud dawn
#

But you got ctx.message.author.avatar_url

#

ctx.message.author.avatar.url is good

#

Also ctx.author.avatar.url is the same.

granite brook
#

was it at some point with a _? I found it like that in some old code I had

slate swan
#

str(ctx.message.author.user.avatar.url)

late ruin
mighty pilot
#

what info do you get from the payload in on_raw_reaction_add

cloud dawn
unkempt canyonBOT
#

class discord.RawReactionActionEvent```
Represents the payload for a [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") or [`on_raw_reaction_remove()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_remove "discord.on_raw_reaction_remove") event.
candid cave
#

Hey guys I'm new here lmao😅

cloud dawn
naive briar
#

Hi 🐈

cloud dawn
mighty pilot
candid cave
#

Guys I'm learning python, made a calculator today...

slate swan
#

oh panda answered

candid cave
#

It would be great if you guyz can help me as a beginner 😅😅

cloud dawn
slate swan
#

also, inconsistent Library design 💀👀

cloud dawn
late ruin
#

earlier it was difrent

cloud dawn
#

!d discord.Embed.set_footer

unkempt canyonBOT
#

set_footer(*, text=None, icon_url=None)```
Sets the footer for the embed content.

This function returns the class instance to allow for fluent-style chaining.
candid cave
#

So I'm trying to know where can I get those materials to learn as easy as I can

cloud dawn
# late ruin

I recommend using the docs, a lot of answers I give you are straight in the docs.

candid cave
#

Because I'm not from any tech. Background!

candid cave
cloud dawn
late ruin
cloud dawn
#

But good advice nonetheless.

late ruin
#

so i can't?

late ruin
regal cove
#

how do i send a message when using slash commands?

cloud dawn
unkempt canyonBOT
#

The timestamp of the embed content. This is an aware datetime. If a naive datetime is passed, it is converted to an aware datetime with the local timezone.

cloud dawn
regal cove
# cloud dawn What have you got so far?

i've been trying to send a message but i cant make it work so i started trying different things. this is my latest attempt

      await discord.Interaction.response.channel.send(f"{member_name}'s balance!\n\nMoney\n$" + str(member_bal), ephemeral = False)
cloud dawn
late ruin
#

there is no example of that 😦

regal cove
# cloud dawn Could you show a bit more code? You are also using derives instead of the given ...
@tree.command(name = 'bal', description='This command will tell you your or someone elses balance') 
async def show_balance(ctx, member: discord.Member = None):
  db = client.database_connection
  cursor = await db.cursor()
  USER_ID = discord.Interaction.user
  USER_NAME = str(discord.Interaction.user)

  
  

  
  await cursor.execute("SELECT user_id FROM money_data WHERE user_name = ?", (USER_NAME,))
  
  result_userID = await cursor.fetchone()

  if not member == None:
    member_id = member.id
    member_name = member.name
    member_id = str(member.id)
    member_name = str(member)
    await cursor.execute("SELECT user_id FROM money_data WHERE user_name = ?", (member_name,))
    result_memberID = await cursor.fetchone()
    if result_memberID == None:
      await cursor.execute("INSERT INTO money_data(user_name, balance, user_id)values(?,?,?)",(member_name, START_BAL, member_id))
      await db.commit()

      await discord.Interaction.response.channel.send(f"Hi, you're a new user and you need to register. \nTo register execute the command one more time!", ephemeral = False)

    else: 
      member_id = str(member.id)
      
      await cursor.execute("SELECT balance FROM money_data WHERE user_id = ?", (member_id,))
      result_memberBal = await cursor.fetchone()
  
    
      member_bal = result_memberBal[0]
      member_bal = str(member_bal)
      await discord.Interaction.response.channel.send(f"{member_name}'s balance!\n\nMoney\n$" + str(member_bal), ephemeral = False)
cloud dawn
regal cove
cloud dawn
brisk rapids
#

Hi I have a problem where I wan't to assign a role but the "ctx" isn't defined and so it doesn't know where to assign it to. I only wan't to use this bot for a single server. ```py
async def StatusUpdater():
with open("member_ids.json", "r") as openfile:
members_list = json.load(openfile)
for d in range(len(members_list)):
#print(members_list[d][1])
temp_timeset= []
JoinedDatetime_str = members_list[d][1]
JoinedDateTime = datetime.strptime(JoinedDatetime_str, '%y/%m/%d/%H/%M/%S')
nowString = datetime.now().strftime("%y/%m/%d/%H/%M/%S")
now = datetime.strptime(nowString,'%y/%m/%d/%H/%M/%S')
#print(now)
timeDifference = now - JoinedDateTime
BadgeStatus = members_list[d][2]
if BadgeStatus == 2:
if timeDifference.total_seconds() > 120:
#await addrole(members_list[d][0], "2 Years")
members_list[d][2]=3
with open("member_ids.json", "w") as outfile:
json.dump(members_list, outfile)

cold sonnet
#

orbán viktor

olive topaz
#

Hello, is posible somehow with python edit user profile custom status? I know this is not bot but I think this would be cool. Thanks

glad cradle
split forge
#

I need help some one can dm me pls thanks.

granite brook
#

hello guys! I started trying out the slash commands for my discord bot (using discord.py)
is it possible to get a context variable out of this?

@bot.tree.command(name = "settings")
@discord.app_commands.describe(change_name = "Turn name change on/off!")
@discord.app_commands.describe(color = "Set your color!")
async def settings(interaction: discord.Interaction, change_name: str = None, color: str = None):
    # code magic
sick birch
unkempt canyonBOT
#

classmethod await from_interaction(interaction, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates a context from a [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction"). This only works on application command based interactions, such as slash commands or context menus.

On slash command based interactions this creates a synthetic [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") that points to an ephemeral message that the command invoker has executed. This means that [`Context.author`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.author "discord.ext.commands.Context.author") returns the member that invoked the command.

In a message context menu based interaction, the [`Context.message`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.message "discord.ext.commands.Context.message") attribute is the message that the command is being executed on. This means that [`Context.author`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.author "discord.ext.commands.Context.author") returns the author of the message being targetted. To get the member that invoked the command then [`discord.Interaction.user`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.user "discord.Interaction.user") should be used instead.

New in version 2.0.
granite brook
#

oooo, nice tyvm :D

atomic wolf
#

Do you guys know of a good IDE for making bots?

atomic wolf
#

I was thinking something with a visual aspect, or maybe the ability to run the program beside the code.

primal token
night crater
#

!or

unkempt canyonBOT
#

When checking if something is equal to one thing or another, you might think that this is possible:

# Incorrect...
if favorite_fruit == 'grapefruit' or 'lemon':
    print("That's a weird favorite fruit to have.")

While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.

So, if you want to check if something is equal to one thing or another, there are two common ways:

# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
    print("That's a weird favorite fruit to have.")

# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
    print("That's a weird favorite fruit to have.")
slate swan
#

Using tiktok.com/@user only shows if user exists, if it's banned or available it shows same result so available users are actually banned

night crater
#

See the embed linked above, but or 204 is always true because it's not how or works

night crater
#

Did you read the embed fully?

slate swan
#

And would check if both values are true

#

Yes

#

No 403/404 can mean available or banned

#

200/202 means its taken

wicked atlas
#

What API are you using?

slate swan
#

But it works

#

He clearly wants to filter banned but I don't think he understands how it works

#

You must use in app check endpoint

#

And the endpoints are hashed so it's sorta advanced stuff

slow zodiac
#

How to create a control panel for the bot?

slate swan
#

If you understand in app tiktok api then yes

#

No there's none on GitHub and so on that work

slow zodiac
#

Where or how do I use it?

#

But where do I put the script

#

Not.

#

I use the vscode platform to use the scripts

#

Ok

elfin glen
#

I'm confused. I've been trying to code a feature to my discord bot to repeat what I say using "!say". Can someone tell me what is wrong with this block of code? @client.command() async def say(ctx, message): await ctx.send(message)

slow zodiac
#

Does anyone know how I can have a control panel for my bot that people can configure my bot like loritta.

sharp isle
#

Im trying to use ffmpeg on mac os but keeps throwing permission denied error when I run the bot even though I used chmod 777 on the file. Any ideas why? Thx

elfin glen
elfin glen
hollow agate
#

Oh okay! Glad you found the issue :)

lapis flower
#
from discord.ui import Select, View
from discord.ext import commands


bot = commands.Bot(command_prefix='$', intents = discord.Intents.all())


@bot.event
async def on_ready():
    print("bot is on ")

class MySelect(View):

    @discord.ui.select(
        placeholder="Payments",
        options=[
                discord.SelectOption(label="Editeed wtv" , value="1" , description="tes123") , 
                discord.SelectOption(label="Editeed wtv" , value="2" , description="tes123"),
                discord.SelectOption(label="Editeed wtv" , value="3" , description="tes123"),
                discord.SelectOption(label="Editeed wtv" , value="4" , description="tes123" , emoji=":credit_card:"),
               
        ]
  )

    async def select_callback(self , select , interaction):
     select.Disabled=False

@bot.command()
async def a(ctx):
    view = MySelect()
    await ctx.send("ff" , view=view)
fading marlin
#

nice code?

grand hazel
#

how do i put a list into a embed text?
like if the list had [1,2,3]
the embed will make 3 field in one large embed

fading marlin
trim shadow
#

why i can not copy link webhook this?
p/s: this webhook created by Bot

upbeat gust
#

You probably can though

trim shadow
upbeat gust
#

I have no idea what you're saying.

grand hazel
#

i made a program that can run multiple bots and the bots are stored in a list, but i want to check if each bot is online, how do i do it?

i used this to run the bots

@client.command()
async def uptime(ctx, token):
    global bot
    try:
        bot.append(discord.Client(intents = discord.Intents.all()))
        await bot[-1].start(token)
    except Exception as e:
        await ctx.send(e)
trim shadow
grand hazel
golden edge
#

fix?

#
from discord.ext import commands

client = commands.bot(command_prefix = '.')

@client.event
async def on_ready():
    print('bot is online by Rex...#0001')

    client.run() ```
slate swan
#

client = commands.Bot(command_prefix='.', intents=discord.Intents.default())

sick birch
#

guys

#

i did a thing

#
struct Handler;

#[async_trait]
impl EventHandler for Handler {
    async fn message(&self, ctx: Context, msg: Message) {
        if msg.content.starts_with("!hello") {
            msg.channel_id.say(&ctx.http, "Hello from Rust! 🚀").await.unwrap();
        }
    }
}

#[tokio::main]
async fn main() {
    let token = "";

    let intents = GatewayIntents::all();

    let mut client = Client::builder(token, intents)
        .event_handler(Handler)
        .await
        .expect("Error creating client.");

    if let Err(why) = client.start().await {
        println!("Client error: {:?}", why);
    }
}
sudden sinew
#

is there any way to add base64 encoded image in embed?

slate swan
#

or there was Twilight crates too

grand hazel
#

code :

bot = []
@client.command()
async def uptime(ctx, token):
    global bot
    try:
        bot.append(discord.Client(intents = discord.Intents.all()))
        await bot[-1].start(token)
    except Exception as e:
        await ctx.send(e)

then i tried printing the username

for i in bot:
    print(bot[i].user.name)

error :

#

help me bro

slate swan
#

what are you even trying to do

grand hazel
slate swan
#

multiple bots under the same loop is not suggested

#

that's not how do it anyways

grand hazel
#

the bot work

slate swan
#

you'll have to use a seperate task

grand hazel
#

i just cant print each bot username

grand hazel
slate swan
#

the bot that gets online later will block processes of the first bot

slate swan
#

what part do you not understand

grand hazel
#

i dont understand because everything worked except printing the bot's username from the list

slate swan
#

because those lines didnt get executed

#

actually no

grand hazel
slate swan
#

your loop doesnt make sense

grand hazel
#

which is true

slate swan
#
for bot in bots:
    print(bots[bot].user.name)
``` this is what you're doing
slate swan
grand hazel
grand hazel
slate swan
slate swan
#

the docs say that its blocking

grand hazel
#
bot.append(discord.Client(intents = discord.Intents.all()))
await bot[-1].start(token)
grand hazel
#

the first code used to look like this

#
import asyncio
import discord

client = discord.Client()

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')

@client.event
async def on_message(message):
    if message.content.startswith('!create_bot'):
        token = message.content.split()[1]
        new_bot = discord.Client()
        await new_bot.start(token)

client.run('YOUR_BOT_TOKEN_HERE')
#

@slate swan

slate swan
#

this is still blocking

grand hazel
#

i dont understand the "blocking" part

slate swan
#

!blocking

unkempt canyonBOT
#

Why do we need asynchronous programming?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.

What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:

import discord

# Bunch of bot code

async def ping(ctx):
    await ctx.send("Pong!")

What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.

async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!

grand hazel
#

it allowed me to do other task while the bot is being executed

slate swan
#

no start doesnt do that, you were misguided

grand hazel
#

hmm

#

can i just show you it?

slate swan
#

sure

grand hazel
slate swan
#

anyone familiar with pycord?

#

not particularly but yes

slate swan
# slate swan not particularly but yes
@bot.slash_command(description='Joins Voice Channel And Play Onegai Sound Effect')
async def onegai(ctx: commands.Context, chanel_id):

    await ctx.respond("Please pound me more with you ")
    channel_id = chanel_id
    voice_channel = bot.get_channel(channel_id)
    # print(voice_channel.name)
    vc = await voice_channel.connect()
    vc.play(discord.FFmpegPCMAudio("./sounds/onegai.mp3"))
    while vc.is_playing():
        await asyncio.sleep(.1)
    await vc.disconnect()```
error:
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'NoneType' object has no attribute 'connect'
#

I am trying to make my bot join a voice channel using its id

#

but having this issue

unkempt canyonBOT
#
Nope.

No documentation found for the requested symbol.

slate swan
#

cul

slate swan
#

i am using py-cord actually

#

both should be the same

#

wait imma check docs

#

pls always consider checking docs

#

docs

#

!d discord.VoiceClient

unkempt canyonBOT
#

class discord.VoiceClient```
Represents a Discord voice connection.

You do not create these, you typically get them from e.g. [`VoiceChannel.connect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceChannel.connect "discord.VoiceChannel.connect").

Warning

In order to use PCM based AudioSources, you must have the opus library installed on your system and loaded through [`opus.load_opus()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.opus.load_opus "discord.opus.load_opus"). Otherwise, your AudioSources must be opus encoded (e.g. using [`FFmpegOpusAudio`](https://discordpy.readthedocs.io/en/latest/api.html#discord.FFmpegOpusAudio "discord.FFmpegOpusAudio")) or the library will not be able to transmit audio.
slate swan
#

@slate swan

slate swan
#

cool

#

cul

#

I got this and reading dis rn

slate swan
slate swan
slate swan
slate swan
#

it will be vc = discord.VoiceClient(bot, channel)

#

according to docs

#

i found it u need to get voice channel

slate swan
slate swan
slate swan