#discord-bots
1 messages · Page 152 of 1
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.
!d discord.Member.guild_permissions
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.
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
Can someone really Experienced in writing discord Bots DM me ? 😋🙏
ah sorry I don't understand 😔
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
are you sure it wouldn't be more productive to just post your question here
this is a channel for bot-related help after all
it's giving me an attribute error
Show your code
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
Ok
what's the best method of round timer to use for rounds in a game?
Do you know what instances are?
you can use discord.Button.disabled and set it to True when the button is clicked, but remember to update the view again afterwards
specific to discord? or do you mean like class instances in python more generally
In Python, of course
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?
Yeah
So you have to get an instance of your target guild
Like from context or interaction or something
!d discord.Guild
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.
💀
That's a class var
It will only affect the instantiated obj
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
ctx.guild is the instantiated Guild object
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(...):
...
closest i am thinking is some kind of predicate or decorator slapped on the real command
i setted self._before_slash_command_invoke myself
fuck decorators, i don't need them
ah okay, thank you. will resume with this in a bit. I appreciate the help from you all!
What's the problem exactly
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
What does that mean
He sorts the txt file as he wants
Why is the fp.seek in the for loop
You keep seeking to the begining every time it loops
Isn't that the way it's supposed to be?
No
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")```
Bruh
Thanks it works
hi guys, how do u make slash commands with dpy?
Third pin
Here are a few examples
tyyyy
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
so like if you change help to anything else you get the same conflict error?
default help command overlapping o.O?
presuming there’s nothing else in the code we can’t see
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
you def cant have this "async def help(ctx)"
why not
help is already an internal keyword
oh..
what command prefix are you using?
than what should i put
but was he not saying any other name still broke? x)
"halp"
like in one of my games it's "/game help"
lol
hmm
just do helpmenu or helpcmd or smth simple
should i put async def mod_help(ctx)
that works
the command you're registering is server wide, so the prefix command is unique to you
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'
user
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
Just after your client stuff put client.remove_command(‘help’)
No
where?
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
)
ooooh
Or like that
thx
bot = commands.Bot(command_prefix="?", intents=intents)
bot.remove_command('help')``` like this @short pulsar ? i dont understand.. im tired sry 😭
Yuh
dosent work
Under that
dosent work 😭
oh
bro I do not know
bot = commands.Bot(command_prefix=“?”, intents=discord.Intents.all()) bot.remove_command(‘help’)
Out of the bot = stuff
do member.edit(roles=[]) remove those roles ?
me ne it her
Yes it does
for me it doesnt 🙂
Any error? Are you awaiting it?, etc
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 []
i did that
bot = commands.Bot(command_prefix="?", intents=intents)
bot.remove_command('help')``` its out the bot =
Hm
PAss intent = discord.Intent.all()
wdym
like x = def()
x will be the return
so
bot = commands.Bot(command_prefix="?")
bot.remove_command('help')```
why does this prints []
like this?
changed code btw
if this is the code.. still dosent work
Intent dosent exist?
andrew
show me the code
from your_file import points should work
i meant intents
oh thats so complicated
bro now nothing works..
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
ok
what's the problem
You don't "transfer" it, you just bind it to your bot instance
you need to do bot.my_variable = points
bro after i changed everything that u said it didnt work
then in your slash command you'll access the variable with self.bot.my_variable
what's the problem
like nothing works not even a old command
uhm
bot = commands.Bot(command_prefix="?", intents=discord.Intents.all())
bot.remove_command('help')
use that
dosent work
yes discord.py
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
bot = commands.Bot(command_prefix="?", intents=discord.Intents.all(), case_insensitive=True)
bot.remove_command('help')
this is my personal code
try using client
dosent work
...
...
...............
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
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.
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
!d discord.Interaction.client
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.
what library are you using
??
@glad cradle he doesn't like bot and client
.
discord.py2
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
there are multiple ways, the simplest is using Literal or enumerations
https://github.com/Rapptz/discord.py/blob/master/examples/app_commands/transformers.py
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
!rule 9
ah i see okay thanks for letting me know
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
>
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?
try to print the type of the interaction and send the output here
Such as the beautifulsoup4 package?
not really?
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!
i mean if you want to scrape specifically Stanford or something like https://pypi.org/project/encyclopedia/
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?
this sounds like a very personal opinion, docs are fine
based on the comments you’re just forcing with copilot or something similar, i would use a package or api to search something, any reason you need stanford in particular?
Well it depends where you putted the print statement 😭
i'm trying to get chatgpt to write it for me
stanford because i am using it as my philosophy bot for my server
with a general python knowledge the docs are quite easy to read imo, you just need a overview of what you are doing
gotcha
ive never seen something more complicated
stanford doesn't seem to have an api
sure docs might be confusing if you’re starting ;p

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 😭
i agree, lots of modules are verrry minimal in the docs and more so seem to tell you where to look in the source to figure it out x)
pip install discord.py
write this to the console
This code will give you error
You are missing intents
Also consider type hint your code. OwO
client = commands.Bot(command_prefix='!',
intents=discord.Intents.all())
✅
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
do you have multiple python versions installed?
~ % python --version
Python 3.9.7
I didn't ask which version you're using
~ % 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
Python 2.7???
it's a list of all the Python executables that are installed on the system, along with their version numbers
where do you see that
check if you have selected the right interpreter in vscode
okay
probably you're installing d.py for a python interpreter thay you're not using in vscode
i will have to install discord.py using pip3.9
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)
~ % /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…
seems like its cuz something blocked the connection to discord.com
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
The guild name.
!d discord.Guild.ban
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.
Can someone tell my why py-cord is helpful please @nocturne hamlet on your answers
how to create thread in discord.py?
!d discord.TextChannel.create_thread
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.
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
make it a task
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
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.
alright
i was definitely about to throw it inside a tasks.loop and just end the loop after the first execution
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)
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
alright cool. thanks
figured naming it was easier to call it out to cancel
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:
Read the error
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
just finished fully implementing my caching stuff in my discord wrapper
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
👀 took like 70 lines per object for me lol
but i implement cache for each object seperately
ah lol
creating the cache is super easy, storing it on runtime is hard
maintaining it is even harder
its just a dictionary in the end
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 
Haven't made a guild object yes so no guild cache for me sadly
@shrewd apex bro push guild object when
all my caching does work though, i promise you that
okay that code is a bit outdated there
thats a progress
this is actually the correct code the first image goes with lol
tonight sir
oh shit wait i didn't realize that was you sarth, whats good man
genuinely thought you were someone random LOL
am stuck with ratelimits and channel objects
thanks to discord for making these many Channel types
ratelimiting was hard tbh, i can show you my shit if you wanna maybe go off of it
other than that im lively
yes please
fuck those, im not bothering with those yet 
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
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
use attrs lib ong
fuck that smh smh
i dont know how to use the attrs lib tbh
never looked into it 💀
https://sawsha-is.gay/8WlAFRtuP.png the amount of 0 and 11's are crazy
crazy how fast 45 seconds go by jesus
have you ever used dataclasses?
only like once
its exactly the same but faster with development
oh
sarth, by chance do you know how to fetch only a specific channel through the api?
isn't there a get channel endpoint
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
https://sawsha-is.gay/f8mBnPPMQ.png oh wait im stupid, i already implemented it LMAO
"channels/{id}"
i made someone ( ahem asher) write a class with all endpoints for me
and i am still waiting for u to keep up to ur commitment ;-;
also sarth did you look at dms about the ratelimit stuff
ohh no sorry lemme see
seems neat, i plan to implement something like discord.py's ratelimit handler tho
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
thats nicee
dude tbh i have way more stars on wharf then i ever expected to have already lol
i took some impl ideas from hikari
like using direct bitfields instead of properties for flags
idky discord.py makes that weird
💀i don't even know who are the 2 people using my Library
it shows used by 2 in dependencies
lmfao
👀 whats that LoC next to SawshaDev/wharf ? some chrome extension?
LoC- lines of code
its github gloc
are you trying to install ssl certificates?
open the python folder and click on install certificates thats all
use a ATTACHMENT type option
!code
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.
depends on the library you're using
hi, could someone tell me what he thinks about my bot (like there are some improvements that he wants to suggest, etc...)
codewise or based on bot's functionality?
codewise 🙏
the bot functionalities are stupid
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)>
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)```
- 88/120 characters
yeah ik, i need to adapt to PEP8, when i writed the basecode i was a noob
https://github.com/Snipy7374/SnipyBot-CodeWithVincentServer/blob/c0430c5c0f788a791f40625ac2d8e9fcdb58bb53/slashCommands/packages_searcher.py#L21 use a dataclass/ attrs.define here! much easier to work with
slashCommands/packages_searcher.py line 21
class Package:```
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")
using a single aiohttp clientsession for the complete bot will be nicer (https://github.com/Snipy7374/SnipyBot-CodeWithVincentServer/blob/c0430c5c0f788a791f40625ac2d8e9fcdb58bb53/slashCommands/packages_searcher.py#L82)
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.
its @bot.command()
What kind of naming convention is this
I don't know any languages where variable names start from capital letter
ehm hows that
I forgot so many things lol
its iMakeMyOwnRules convention
What for is random.choice in a set lol
f strings gone wrong
i just realised python's pep page is hosted on github pages lmaooo
bro dm?
Wtg
Wth*
see for yourself https://peps.python.org/pep-0069/
i was looking for pep69
Javascript: hi
ohh my bad, this dm request feature is annoying
404 GOES BRRRRRRRRRR
i didnt get a notif from you
agreeeeed
They doesn't even give notification
Js uses lowerCamelCase for vars
This is definitely IMakeMyOwnRules
Imho it's useful but no notifications is absurd
exactly, i don't even get to notice if someone new sent a dm
its more fked up on mobile client
Mobile client used to be a giant f itself
All knows 🤷
It still is but not that giant
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"
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!
ahhh this is like my first proper bot so i have no idea either 😭
ahhh thank you!!1
One sec
My PR recently got merged
This guide shows how to host a bot with Docker and GitHub Actions on Ubuntu VPS
Their markdown processor smokes smth
is there a way to construct the Package object passing my dict as **dict?
!e ```py
import dataclasses
@dataclasses.dataclass(kw_only=True, repr=True)
class Package:
url: str
name: str
data = {"name": "hehe", "url": "amogus.com"}
print(Package(**data))
but iirc this is only for python >= 3.10
!pypi attrs
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))
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
Package(url='amogus.com', name='hehe')
you're the second person that talks about attrs so ig i'll look into it
how do i remove this cuz when i want to click tab this pops up and it annoying
well turn off github copilot :man_pain:
how ?
google "how to disable a plugin/extension in <your ide/editor name here>"
you said github copilot right ?
yes
i dont even have that extension
but still thanku for your time
well then its some other extension that provides autocompletes like that
might be tabnine or something
you have to give a custom id to all options if you want to make a persistent drop down menu?
yes
isn't the select menu to which the custom ID is set?
all i remember is that all components with custom_id option should have it provided
yes but SelectOption isn't a component
ye
there is no custom id here
you dont need it
!d discord.ui.Select
just add a custom_id for the select
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.
you set a custom id for the dropdown menu (aka select) not for the options
docs says it will autogenerate it
still should i add it?
for persistent views/components you need to set it
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:
@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)
youtube tuwutorials You need to sync the commands too
Hey @thorny frost!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
rate limit?
wtf is that?
are u using repl?
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
yeah repl is causing your bot to get ratelimited
i new to repl
so what now
too many requests to discord, extremely common on repl because its shared ip's
just host somewhere else
hmm so now?
where?
just do kill 1 in the shell, that'll fix it (for some time)
if you got card verification, use oracle cloud
otherwise check the pins, theres a message all about hosting a bot
i don't wanna pay no money
what's card verification?
you need to verify a card, but it wont charge
im so confused tho. i did the same thing on this bot as on another bot and the other bot works
can i do that with a fake credit card?
why does one work and another dont when they have the same code (not the same commands)
lol idk
i tried it with spotify and got 3months of premium
it's patched nwo
just use a legit card ¯_(ツ)_/¯
bro i'm a minor
slash commands have to be synced
16
become a major 🛐
i had slash commands on the other bot and for some reason that one worked but not this one
host locally, old laptop, or raspberri pi then
in 2 years
so the laptop keeps running 24/7?
yeah
which library?
🛑 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...
is this legit?
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
show your aclient class only, whole of it
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)
idk man im not here to teach ya to bypass payment/verification walls
you aren't syncing your commands anywhere really, sync them inside a setup_hook (recommended)
class aclient(...):
...
async def setup_hook(self) -> None:
await self.tree.sync() #global sync
#you can pass in a discord.Object object containing your guild id to sync it to just one server/guild```
discord.py mods coming after you 😂
that's exactly what you were asked to use by them
💀
oracle doesnt allow fake ccs
they have a complete tag called ass for this , creative naming skills
lmao
omg bro im so stupid
i copied my code from one but forgot to copy the on_ready function which is where i synced the commands
don't sync inside on_ready smh
discord.py may hit on_ready multiple times
persistent views for buttons and selections are almost same right?
yes
yato 🛐
Otters 🛐
but i have a thing in my code that makes sure no commands are synced twice
so that should be fine
you 🛐
i gave custom id value and did same as buttons, still persistent view not working
nou 🛐
nou 🛐
that's sad
fr it is
eevee 🛐
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
how?
idk, i neither use replit, nor suggest it
you can google
so rude 🛐
back
I tried to google but nothing came up
i find it better than making someone use that service just to realise that its trash for hosting a bot
1 min
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
didn't work
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.
Is there any way to get audit log like event
@slate swan
U there
yes
how to install a package in windows vs terminal 🤷
pip install package-name
pip is not recognized error
....
For a guy
python -m pip
Did u set the view's timeout=None
yep
it should be like this eh?
or this can work too?
This will work
but its not 🤡
its saying custom id and options are required
and i have given them, still saying they are required
What
Sir sir big fan
Are you sure that your customid variable is not none
Autograph pls
Or options even
works but still dont want it like that
It's a list doesn't mean it always has any elements in it
i ran it before the decorator
on printing they will be none because they will get values from user
don't use "" as custom id lol
i added custom id as an argument in command
i changed nothing and the error is this now 🤡
Clown emoji 💀
🤡 .
You don't have timeout arg in your subclass init signature
i have it
Where bro
except the options thing is everything good?
ouch
'.format(client))```
what is wrong?
added it
is everything else as it should be?
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()```
its imp otherwise the dropdown menu would stop working after few mins right?
"Outdated" way of formatting strings, nothing else
!f-strings
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.
You provide it in superclass init
thanks bro
yep
what is wront now 😭 ?
Discord is now 2 gb on mobile wtf
@vale wing are you free rn? I want help with making persistent views for select options
can you help?
Are you following some outdated tutorials (you are)
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...
Not really comfortable to do that from phone sry
AHAH
The fcc tutorial
well kek
Honestly I don't even know what modern tutorial to recommend
!resources maybe look there
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
just tell me is it as it should be? it will help
I just got home from 1 week work trip and jetbrains new design got me like
crazy shit
Could you maybe start collab session, it would be more comfortable for me to help you
i dont even know what a collab session is
is it something inside visual studio code?
do you can recomend tutorial not outdated with slash commands?
Yeah I think
Bro wut 💀
pass timeout when u call it not when u init it
Vise versa
anyoen help
it shows this error
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'coroutine' object is not callable
Await it
wdym
I literally did this
await ctx.send("We generated the 3 safest mines. :cozysip: ")(random.choice(MinesList))
!async-await
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.
await ctx.send("We generated the 3 safest mines.")(random.choice(MinesList))
What is that supposed to mean
it says "we generated the safest mines and then sends a random thing from the list I wrote
Then use f-string to put it in the string before sending it
!f-string
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.
no like how do I fix this??
await ctx.send("We generated the 3 safest mines. :cozysip: ")(f"random.choice(MinesList)")
Remove what ever you're trying to do after the ctx.send
like this or what?
Do you know how functions work
kinda, I haven't coded for a year so its hard
!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())
@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
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?
I just said it
Remove whatever you're trying to do after the ctx.send
then it won't work tho
And is the current one works?
Ik what u r trying to do
that one wont work either tho
U r trying to take random 3 str from a list obj
And send it
I'm trying to take one thing from the list
its like a link that has 3 things in it
Only 1?
Ok
Someone explain to him
xd
I'm out
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.
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

Still xd
He is trying to take something from ah whatever
from ah whatever?
I am out too 🗿
🤔
globals().get("ah whatever", TypeError("skill issue"))
😂😂
I have aah coding issues
Just because of this shit exam
go study
2 more exam and me free
exam = 2
if exam == 0:
spooky.release('freedom')```
That will never happen according to this coding 🗿
i don't have any exams anytime soon
jan?
thats 1 month
not preparing for Jan session, coaching teachers straightforward said they'll complete the syllabus in mid-feb lol
💀
go study
"soon"
neh 💀 imma watch fifa or john wick
i forgor to watch spyxfam again
1 month is 1/12th of a year
is it the right way to make the persistent view?
Why u passing timeout in __init__
well fuck
now its in super only
good eh?
Yes good meh
everything else is right?
i just have to solve the options problem then
Yes meh
Try printing option after executing command
I mean after interaction
in terminal?
<@&831776746206265384>
is replit down?
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'
ctx.author.id
Probably
The thing is so bad you can't tell the difference
Why is there a ctx in a slash command callback
damn
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'```
interaction.user
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)
!d discord.Interaction.user
The user or member that sent the interaction.
how to fix that error?
What error?
!d discord.Asset.url
property url```
Returns the underlying URL of the asset.
!d discord.User.avatar
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").
so change ctx.message.author.avatar.url to discord.User.avatar?
But you got ctx.message.author.avatar_url
ctx.message.author.avatar.url is good
Also ctx.author.avatar.url is the same.
was it at some point with a _? I found it like that in some old code I had
1.7.3
str(ctx.message.author.user.avatar.url)
but it doesn't work and i don't know what to do
what info do you get from the payload in on_raw_reaction_add
!d discord.RawReactionActionEvent
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.
Hey guys I'm new here lmao😅
Show the error.
Hi 🐈
Hi new here
appreciate you
Guys I'm learning python, made a calculator today...
oh panda answered
It would be great if you guyz can help me as a beginner 😅😅
gotchu
also, inconsistent Library design 💀👀
What exactly do you need help with?
!d discord.Embed.set_footer
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.
I've seen a lot of people saying we need to focus on the basics a lot to learn to code
So I'm trying to know where can I get those materials to learn as easy as I can
I recommend using the docs, a lot of answers I give you are straight in the docs.
Because I'm not from any tech. Background!
I'll be amazed man I appreciate you
That message was not for you :3
i tried but i can't find how to add timestamp
But good advice nonetheless.
so i can't?
Depends on where you start.
like date and time
how do i send a message when using slash commands?
!d discord.Embed.timestamp
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.
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)
Could you show a bit more code? You are also using derives instead of the given constructor.
there is no example of that 😦
@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)
it's just embed.timestamp = ...
await interaction.response.send_message(...)
I recommend checking this out -> https://github.com/Rapptz/discord.py/blob/master/examples/app_commands/basic.py
i tried that for some reason it didnt work
Because you pass ctx in the function. Interaction is for slash command. You are mixing message commands and slash right now.
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)
orbán viktor
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
nope
@slate swan how's now https://github.com/Snipy7374/SnipyBot-CodeWithVincentServer/blob/master/slash_commands/packages_searcher.py
I need help some one can dm me pls thanks.
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
!d discord.ext.commands.Context.from_interaction
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.
oooo, nice tyvm :D
Do you guys know of a good IDE for making bots?
Emacs 
I was thinking something with a visual aspect, or maybe the ability to run the program beside the code.
Vs code is nice for a lightweight IDE, which can do that
!or
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.")
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
See the embed linked above, but or 204 is always true because it's not how or works
And would check if both values are true
Yes
No 403/404 can mean available or banned
200/202 means its taken
What API are you using?
He's using tiktok api the wrong way
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
How to create a control panel for the bot?
If you understand in app tiktok api then yes
No there's none on GitHub and so on that work
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
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)
Does anyone know how I can have a control panel for my bot that people can configure my bot like loritta.
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
✨ indentation ✨
Lol, it is indented in the actual program. It was hard to re-indent it when typing it out.
Do you get any errors?
Sorry, disregard! Someone was able to help me in the forum section.
Oh okay! Glad you found the issue :)
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)
nice code?
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
I've already answered you in #1051320634745028609
why i can not copy link webhook this?
p/s: this webhook created by Bot
Idk I can't read the error
You probably can though
no, this not error, i only ask create webhook from a bot, user can not copy link wk, right?
I have no idea what you're saying.
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)
but why
just a fun little project
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() ```
client = commands.Bot(command_prefix='.', intents=discord.Intents.default())
thanks bro
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);
}
}
rust!!!!
is there any way to add base64 encoded image in embed?
serenity-rs?
or there was Twilight crates too
congratulations 🦀
Danggg dawg
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
what are you even trying to do
make multiple bots online in 1 file
the bot work
you'll have to use a seperate task
i just cant print each bot username
the bot work, it actually make other bots online, i just cant print their username
the bot that gets online later will block processes of the first bot
what part do you not understand
i dont understand because everything worked except printing the bot's username from the list
which one? printing the username?
your loop doesnt make sense
they said client start means it will run on the background
which is true
for bot in bots:
print(bots[bot].user.name)
``` this is what you're doing
who said that?
idk random dude
yes, and the "bots" are a list
and lists are indexed with numbers, not bot objects
what makes you trust what a random dude more than your interpreter lol
the docs say that its blocking
bot.append(discord.Client(intents = discord.Intents.all()))
await bot[-1].start(token)
wait
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
this is still blocking
i dont understand the "blocking" part
!blocking
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!
it allowed me to do other task while the bot is being executed
no start doesnt do that, you were misguided
sure
check your dms
@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
!d nextcord.channel.connect
No documentation found for the requested symbol.
cul
nextcord?
i am using py-cord actually
both should be the same
wait imma check docs
pls always consider checking docs
docs
!d discord.VoiceClient
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
hmm thanks i am looking at docs rn
cool
cul
I got this and reading dis rn
also u should probably convert channel id to int it may return in string\
I did and it still gave the nonetype error
https://docs.pycord.dev/en/stable/api/voice.html
nice
it will be vc = discord.VoiceClient(bot, channel)
according to docs
i found it u need to get voice channel
ctx.get_channel?
maybe diff lemme read more
typehint the chenel_id argument to int

