#discord-bots
1 messages Β· Page 1104 of 1
that's not his issue
you werent calling it right maybe?

wait what is he trying to do?
this, not just embed=discord.Embed
make an embed

what in new row?
for guild in bot.guilds:
for channel in guild.text_channels:
link = await channel.create_invite(max_age=300)
await ctx.send(link)```
this is a bad way but how can i get the first channel of every guild and make a invite?
oh i have a snipet for this
number
ah ok
i forgot the @ when i copy pasted but its there in my code
The row u want the buttons to be in. I think it starts with 0
ohk
i dont want a title tho
try not putting anything in the brackets then
@sonic flax try this:
embed = Embed(title="title", description="whatever")
iirc it will error
...
no my error is
dew you just missed ()
I get discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: set_author() missing 1 required positional argument: 'self' when I use this code
@bot.command()
@has_permissions(administrator=True)
async def help(ctx, command=None):
if command is None:
embed=discord.Embed("Commands")
embed.set_author(name=bot.user.name, icon_url=bot.user.avatar_url)```
that's why you got the error before
i still got it when idid it now
bruh
oh, huh. never tried making an embed without a title or anything. was kinda guessing it needed data but that also can be a problem lol
title="Commands"
why you don't you command group?
yeah I also think it has to have a title or a description at least
idk what command grouping is
pretty sure yeah.
@bot.command(invoke_without_command = True)
async def help(ctx):
embed=discord.Embed(title = "Commands")
embed.set_author(name=bot.user.name, icon_url=bot.user.avatar_url)
await ctx.send(embed = embed)
@bot.command()
async def showguilds(ctx):
for guild in bot.guilds:
for channel in guild.text_channels:
link = await channel.create_invite(max_age=300)
await ctx.send(link)```
it sends links for the amount of channels in every guild that's the only method i found, what other methods can i use to create 1 link for each guild
w h y n o t s u b c l a s s H e l p C o m m a n d t h e n
and
@help.command()
async def ping(ctx):
await ctx.send("Hello World")
well i want to be able to do .help (command) and it shows something else
I mean if we really overkill with command grouping, why not do it the right way and subclass HelpCommand
yea
he want custom help command

I get discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: set_author() missing 1 required positional argument: 'self' when I use this code
@bot.command()
@has_permissions(administrator=True)
async def help(ctx, command=None):
if command is None:
embed=discord.Embed("Commands")
embed.set_author(name=bot.user.name, icon_url=bot.user.avatar_url)```
did you remove help ?
@bot.command()
@has_permissions(administrator=True)
async def help(ctx, command=None):
if command is None:
embed=discord.Embed(title="Commands")
embed.set_author(name=bot.user.name, icon_url=bot.user.avatar_url)β
yes
pep8 disagrees 
I'm not sure how not putting title= makes the code not make an instance
I thought pep8 wants the space before and after the equation sign in a kwarg
I haven't seen the pep8 officer in a while
@bot.command()
@has_permissions(administrator=True)
async def help(ctx, command=None):
if command is None:
embed=discord.Embed(title="Commands")
embed.set_author(name=bot.user.name, icon_url=bot.user.avatar_url)
await ctx.send(embed=embed)
Now i get discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: init() takes 1 positional argument but 2 were given
show traceback
bot = commands.Bot(command_prefix = "Your Prefix", help_command = None)
I'm confusion
i have that
how did you come to that conclusion
π€
πΏ
idk π
oh
you forgot to restart the bot
restart the bot
once putting the right code
old code
embed=discord.Embed(title="Commands") and restart the bot

same
mutual feelings
a little different cus im using slash commands but im sure you can adopt it.
@slash.slash(
name="help",
guild_ids=servers
)
@commands.has_permissions(administrator=True)
async def _help(ctx:SlashContext):
embed = Embed(title='Commands')
embed.set_author(name=client.user.name,icon_url=client.user.avatar_url)
await ctx.send(embed=embed)
poorly thrown together but should work.
yeah i just ran it and it works so its an issue with somethin else he has
yeah only 4 of us have said it already
discord_slash s.m.h.
@bot.command()
async def showguilds(ctx):
for guild in bot.guilds:
for channel in guild.text_channels:
link = await channel.create_invite(max_age=300)
await ctx.send(link)```
it sends links for the amount of channels in every guild that's the only method i found, what other methods can i use to create 1 link for each guild
your bot's gonna get ratelimited AAAAAAA
generate only 1 link for that guild, and then continue
im asking how
if it's under a for loop, thats what ruins it
[await ctx.send(await guild.text_channels[0].create_invite(max_age=300)) for guild in bot.guilds if guild.text_channels]
``` sheesh
though it's better to just send them all at once
await ctx.send("\n".join([(await guild.text_channels[0].create_invite(max_age=300)).url for guild in bot.guilds if guild.text_channels])
though it's privacy breaching as I've said it multiple times before
since people could have your bot in private servers
with content to not be seen by other people
with your bot being in the server, you could get an invite which will just result in your bot getting reported multiple times leading to further consequences
π
send a generator object?
dunno, never worked with invites
@heady sluice :white_check_mark: Your eval job has completed with return code 0.
<generator object <genexpr> at 0x7f455c7dfca0>
hah
no?
[await ctx.send(
await guild.text_channels[0].create_invite(max_age=300)
)
for guild in bot.guilds
if guild.text_channels]
``` read it now
I hate reading this
ok
!e
''' Don't tell me that am repeating, an uwu example is required forsure '''
[print(uwu) for uwu in ["uwu1", "uwu2", "uwu3"]]
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | uwu1
002 | uwu2
003 | uwu3
@disnake.ui.button(label="h", style=ButtonStyle.gray)
async def but1(self, button: disnake.ui.Button, interaction: disnake.MessageInteraction):
if interaction.author == self.user or self.challanger:
if self.chance == 1 and interaction.author == self.user:
button.emoji = "π΄"
button.style=ButtonStyle.green
button.disabled = True
self.chance = 2
await interaction.response.send_message("Selected",ephemeral=True)
elif self.chance == 2 and interaction.author == self.challanger:
button.emoji = "β"
button.style=ButtonStyle.red
button.disabled = True
self.chance = 1
await interaction.response.send_message("Selected",ephemeral=True)
π why this doesnt change emoji and disbable the button and change the color
How bots Doesn't tag the role like they use @everyone tag yet the role isnt mentioned
did you edit the message with the view
!d discord.AllowedMentions in .send /.reply or your Bot constrctor
class discord.AllowedMentions(*, everyone=True, users=True, roles=True, replied_user=True)```
A class that represents what mentions are allowed in a message.
This class can be set during [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") initialisation to apply to every message sent. It can also be applied on a per message basis via [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for more fine-grained control.
!e pwint = print '''Don't teww me that am wepeating, an uwu exampwe is wequiwed fowsuwe ''' [pwint(uwu) for uwu in ["uwu1", "uwu2", "uwu3"]] #>_>
ew
it's getting worse and worse
!e
for x in range(3):
print(f"uwu{x+1}")
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | uwu1
002 | uwu2
003 | uwu3
no
Hi guys
hello
I'm building a discord robot now, does anyone have any theoretical ideas? I mean, what options should I put on the robot?
do that
uh wait
good idea, my next sentences awe gonna come out wike thiws
What else can you expect
wowse and wowse
you uwu
I'm deleting discord
Iβm reporting you
suwe, no wowwies
@disnake.ui.button(label="** **", style=ButtonStyle.gray)
async def but1(self, button: disnake.ui.Button, interaction: disnake.MessageInteraction):
if interaction.author == self.user or self.challanger:
if self.chance == 1 and interaction.author == self.user:
await interaction.response.edit_message("Selected")
button.emoji = "π΄"
button.style=ButtonStyle.green
button.disabled = True
self.chance = 2
elif self.chance == 2 and interaction.author == self.challanger:
await interaction.response.edit_message("Selected")
button.emoji = "β"
button.style=ButtonStyle.red
button.disabled = True
self.chance = 1
this doesnt work...
class Main(commands.Bot):
def __init__(self):
super().__init__(
command_prefix = ".",
intents = discord.Intents.all(),
application_id=986411930954629131) # Client ID
async def on_ready(self):
print(f'{self.user} has initialized.')
async def setup_hook(self):
self.initial_extensions = [
'cogs.general',
'cogs.suggestion',
]
for ext in self.initial_extensions:
await self.load_extension(ext)
# Guild ID
await bot.tree.sync(guild=discord.Object(id=981034070421155850))
@app_commands.command(name='load', description='Enable a command')
@app_commands.describe(extension="Command Name")
async def load(self, interaction: discord.Interaction, extension: str):
bot.load_extension(f'cogs.{extension}')
@app_commands.command(name='unload', description='Disable a command')
@app_commands.describe(extension="Command Name")
async def unload(self, interaction: discord.Interaction, extension: str):
bot.unload_extensions(f'cogs.{extension}')
@app_commands.command(name='reload', description='Reload a command')
@app_commands.describe(extension="Command Name")
async def reload(self, interaction: discord.Interaction, extension: str):
if extension in ['all', '*']:
for ext in self.initial_extensions:
bot.unload_extension(ext)
await self.load_extension(ext)
else:
bot.unload_extension(f'cogs.{extension}')
bot.load_extension(f'cogs.{extension}')
Anyone know why the @app_commands.command lines don't show up? I dont get any errors they just dont load in I guess because I dont have them as cogs
jesus
await self.ctx.send(view=Match(self.bot,self.user,self.challanger,self.ctx))
..
you shall edit this message with self where self is the view with the button
wait I just realised
is interaction.response this message?
..?
I don't know how you could access this message without saving it to a variable
u mean to edit the message that has the view if yes interaction.response.edit_message do that
!d discord.InteractionResponse.edit_message
await edit_message(*, content=..., embed=..., embeds=..., attachments=..., view=..., allowed_mentions=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by editing the original message of a component or modal interaction.
..
seems good
lmao
awaig interaction.response.edit_message("Selected", view=self)
at the end of the code...?
cuz you put it at the start
π lol i forgot that ye thats the problem
I'd be happy if that worked
thanks :D
it worked
!d discord.abc.Messageable.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
So?
no?
I said to use the embeds kwarg and that syntax in invalid
maybe learn python and read the docs
I learning
then learn first
yerl chad lmaoooo
ok
Thanks
await ctx.send(embeds=[embed1, embed2])
oh
im late again ;/
Itβs the thought that counts
def check(m):
urls = list()
urls = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', message.content)
if urls or m.attachments:
return True
return False
I want to check message contains urls or attachements, is that correct?
thats exactly what my dad said
right before he left to buy milk 
sad
!e ```py
import re
print(re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+',"http://nevergonnagiveyou.up but with more text"))
i guess yeah
@slate swan :white_check_mark: Your eval job has completed with return code 0.
['http://nevergonnagiveyou.up']
yea
Because like...
msg = await client.wait_for('message', check=check)
if msg.content.lower() == 'cancel':
return False
else:
if msg.attachments:
img_uploads = [x.url for x in msg.attachments if x.content_type.startswith('images')]
print(img_uploads)
urls = list()
urls = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', message.content)
print(urls)
send = (',').join(urls + img_uploads)
if send:
return send
else:
return None
It returns an empty list i'm so pissed XD
There is a limit of 15 on Option choices right ?
how do i define ctx for a command that is in a diff file? i have my main game running in my core file, with it referencing a second file for the game choices. i have got to a point tho where i am tryin to use a wait.for, and i cant use bot or ctx because there is no context for it
you want to invoke command A from within an event I guess?
i believe so yeah
try now to be as specific as possible, including code
actually no
both of them
ImportError: cannot import name 'music_cog' from 'music_cog'
does somebody knows how i can fix this?
it's pissing me off i can't fix it XD
i totally dont know how I could
is your regex correct?
try adding
r in front of the string
so r'https?://......'
from music_cog import music_cog
show your folder structure as well as your import attempt
lemme test it. Also thing is it's not detecting the attachments
you don't even have to import the file to load it
We don't help with music bots.
get the command first (Bot.get_command), then invoke it using the invoke method (Command.invoke) with the required arguments
basically, the entire code is set up within 1 command (new_game), than references defs in a separate file to provide a multi choice option, and to provide the text. the issue is when i try to use
Choice = await ctx.wait_for('message', check=lambda m: m.content.lower() in ['a', 'b'] and m.channel == game_channel)
if Choice.content.lower() == 'a':
like i would in the main file, it cant reference the bot
i believe i got it right anyways
or ctx.message.get_context().bot.wait_for
ctx.bot.wait_for :)
or ctx.message.get_context().message.get_context().message.get_context().message.get_context().message.get_context().bot.wait_for()
yeah ig the regex is incorrect
my bad it doesn't exist
!d discord.ext.commands.Bot.get_context (message)
await get_context(origin, /, *, cls=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Returns the invocation context from the message or interaction.
This is a more low-level counter-part for [`process_commands()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.process_commands "discord.ext.commands.Bot.process_commands") to allow users more fine grained control over the processing.
The returned context is not guaranteed to be a valid invocation context, [`Context.valid`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.valid "discord.ext.commands.Context.valid") must be checked to make sure it is. If the context is not valid then it is not a valid candidate to be invoked under [`invoke()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").
Note
In order for the custom context to be used inside an interaction-based context (such as [`HybridCommand`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.HybridCommand "discord.ext.commands.HybridCommand")) then this method must be overridden to return that class...
typo smh
you can check through regex validators online
its origin in 2.0 cause slashhhhh
@unkempt canyon eval be like
lmao
bruh π
ohhhh nice info thank you !
considering it still doesnt recognise either bot nor ctx, still got an issue :l
can we return to this

you probably don't define the check in the command
but even then it should recognize bot
you don't use a check function
I have to sleep
bruh check or not the check works with the context
shows where you declare the command
con = ctx; bot = con.bot; msg = con.message; cont = bot.get_context(msg); bott = cont.bot; conn = cont; bott = conn.bot; ...
better
the command is in file 1, while the def is in file 2. thats where the issue is i think, as i cant just import bot or somethin
please don't
decorators take a function as parameter how you've even done that
you're forgetting something, await ctx.channel.fetch_message(ctx.message.id)
so its always updated
do you use cogs
thats gonna mess up the way the code is written atm, trying to work out how to make it work with the current rig if possible
i remember someone explaining em to me, but no i dont
genius
@potent spear thanks a million times for your idea !
The regex was incorrect, and it was only capturing a https://www.example.com
Correct regex is:
((http|https)\:\/\/)?[a-zA-Z0-9\.\/\?\:@\-_=#]+\.([a-zA-Z]){2,6}([a-zA-Z0-9\.\&\/\?\:@\-_=#])*
This shit captures ANY link
bruh decorators must be declare above a command you can't write a decorator and then pretend that it will works for an outside function
that's kind of horrible news
I kinda wanna just ask BlvckTvrsier's question again
how did you do @bot.command()
without bot
@my_deco()
def my_func():
```this works
```py
def my_func():
#code
@my_deco()
my_func()
this doesn't
what does def2 do?
@bot.command(name="new_game")
@commands.check(new_game_check)
async def command_new_game(ctx: commands.Context):
await ctx.message.delete()
thats in the main file
but the wait_for im tryin to do is within a definition in file 2
π
its how it was suggested to me when i was writing it ;-;
havent been doing this long so if i shoulda been doing it differently, lmk why lol
have you read the error?
what's there to not understand? it's in plain english
last line
okay i am actually convinced that everyone in this channel are just bots that are programmed to just post tracebacks and do nothing
close
Lol
He is using json so replit or heroku if he is hosting it somewhere
probably some rpi or something
and he messed up the json to the point where it's a huge file or something
mhm
databases exist yk (im a hypocrite)
yeah, he followed a yt video, that's for sure
databases exists yeah, but why don't use a javascript object notation as a database?
what files are on it? (the device)
it's not its intended use, a json is shit for that
how much free space do you have?
seems normal, what other files do you have
tbh #discord-bots is for json help as much as discord bot help
do you even know what you wrote? xd
how much free space do you have on your plan?
F
Bro
im not asking about your json file
Where are u hosting ur bot
and how much space do you have?
Which hosting
which one
3tb?
3 what?
Or 3 bytes π
{ "number": 136, "roast": "weee" },
{ "number": 137, "roast": "we" }``` how can I randomize these ?
bits
Bruh
3 potatoes
Lol
how much total space do you have on hosting site?
He's trolling
i have about 600 mb of free space where i host my bot
U using replit right
how much do you have?
{ "number": 132, "roast": "You shouldn't play hide and seek, no one would look for you." },
{ "number": 133, "roast": "You're so ugly, when you threw a boomerang it didn't come back." },
{ "number": 134, "roast": "The clothes you wear are so ugly even a scarecrow wouldn't wear them." },
{ "number": 135, "roast": "You're so ugly, when you got robbed, the robbers made you wear their masks." },``` how can I randomize these as the result for running the command?
Theb
(sigh) the random module
yeah how do I call the roasts
wait what
oh lord
okay am blind
what is the structure of your file?
Why did I see that as a list twice...
your structure is a bit fucked
{
"number":
{
"132": "shit",
"133": "poop",
"134": "fart"
}
}```
seems cleaner
iirc you can use lists in json
!e
import json
json.dumps("['1', '2', '3' ]")
@quaint epoch :warning: Your eval job has completed with return code 0.
[No output]
yeah, but then you wouldn't be able to ["132"] or similar
guys is there a way to implement cogs in other projects?
just use lists
you don't need the numbers
anyways, if that's the case, he should use a db
what "other projects"?
Wdym by other projects
so how do I randomize the roasts?
besides discord.py
then get the output
use a list instead in the json file
is there an alternative?
Can 1 cog used by 2 main files?
your dict structure is weird
yessir
Depends on the lib u r using
bro
ok
Wow cool
that's NOT what we are asking
@quaint epoch he's trolling for sure
how many mb of space do you have?
Ya..
Cool
π
tl;dr you don't have enough space on your device, find which files are taking up the space and fix it
U know what's storage size
see? i have 725 gb of 953gb space, how much space do you have?
1941 lines doesn't cross 1mb I recon
it don't
Wow 1tb only on c drive
which is why it isn't the problem
sorry but im not a hardcore data scientist in my spare time like eivl
oh ok
What evil things do u do?
games, programming, school, incognito social
okay, now
how much data are you writing to the json?
because it should be less than 50 kb i bet
cya
@slate swan you take care of this
and hunter too
π
spaces between code like ```
a = "hi"
To
a="hi"
take care of?
https://www.youtube.com/watch?v=2cEgb_DEybo
Nice, Discord
No more bad words. Learn how to use AutoMod here: https://dis.gd/automod
β look at us goooooooooooooooooooooooo β
buy Nitro: https://discord.com/nitro
Twitter: https://twitter.com/discord
Instagram: https://www.instagram.com/discord
Facebook: https://www.facebook.com/discord
TikTok: https://www.tiktok.com/@discord
hat guy
thank god he doesn't even think of me when he sees json
oh well, fine, thanks
Watch it completely lol
i see u π you gotta help
that's not what's happening
most likely, you're just never writing to it
ohok
π
Listen like it's saying ex ur space is like 10mb and ur files have used all 10mb so it's raising the error
the device where you're hosting the bot π§
half of the space is empty
Which hosting bte
64mb ram sadgr
I just want to cry, discord gives me a heartbreak
They make good animations
does that 4th shit mean ram
How u not dead then, u must get a heart attack everyday
Yes
62MB for a small bot
haha...........?
damn
reminded me of power rangers
I guess that is what they wanted
or my thinking's way too weird Β―_(γ)_/Β―
Power Rangers are bots like Dynos and MEE6 and uh, automod is.... automod
Nice, one of my servers actually got Automod
automod really cracks me up when I can't send a message due to a dumb word being blacklisted
Don't use dumb words ....
Eh, I don't really think many servers gonna use it anyways since they don't really care about swears
Imagine writing a paragraph then at last ur msg got deleted
thankfully automod takes care of that
out of the 96 servers I am in, in about 90 (if not all) don't give a fuck about swearing
the question here is: would mods be spammed with messages that got "deleted"?
!ot <-
Off-topic channel: #ot2-never-nesterβs-nightmare
Please read our off-topic etiquette before participating in conversations.
π₯΄
I believe we have automod configured here to some extent, I've seen the warning messages in internal channels before (i think)
A channel is gonna get spammed
U count servers damn
Discord sent me a notification to buy nitro cz I am in 96 servers
So I am in ~96 servers
100 is max
Ik
200 with nitro
Discord tryna get bread
potatoes :)
better than adverts on the app
they came out with the idea of nitro on morning potatoes
Of course, they thought of the idea of Nitro over morning breakfast potatoes
Damn it I am slow
That is a relief, agreed
So... They already have potatoes now they are trying to get bread
anyone else got an idea short of using cogs
Does anyone know how to make a system for my bot to publish messages in the announce channels?
but bot publish
!d discord.Message.publish
await publish()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Publishes this message to your announcement channel.
You must have the [`send_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.send_messages "discord.Permissions.send_messages") permission to do this.
If the message is not your own then the [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission is also needed.
discord.Message has to be the actual instance
Yes?
can bots get message in dms of the user
Yes
how
I believe so, yes
You need the actual instance of discord.Message, not the class itself
haaaa ok
Replace discord.Message with ur msg
!d discord.Member.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the destinationβs message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.
Examples
Usage...
but i need this to send embed
do i need to create a class?
Why are you trying to publish if you just need to send an embed?
You're aware of what publishing does?
yes
a = await ctx.send()
await a.publish()
i need something like this for my bot
because my bot has some systems that stop working when I restart
embed = discord.Embed(...) # construct embed
msg = await ctx.send(..., embed=embed)
await msg.publish()
like ticket system
thanks
no prob
I can't use ctx
slash comamnd
I will test this
hello .. I am new here . I know C programming and want to learn Python now .. where can i find help ??
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
here are some good resources for learning python
so I can learn python from the basics right ??
my teacher says that as i know C Programming, i will find python easier
Yeah
Python is much easier from c
error
discord.app_commands.errors.CommandInvokeError: Command 'reiniciar' raised an exception: AttributeError: 'NoneType' object has no attribute '_state'
Use like this u can't just use discord.Message
but ctx gives error
Replace discord.Messsage with msg
..
Dear, please tell me why it gives an error?
thanks i will check those
@slate swan
wtf
who's dear
it's Robin isn't it
ok
Slash commands have interaction not context
I respect you all.
remove ctx.guild.id from the arguments
that's nice of u
I will test, thanks

Thanks
discord.app_commands.errors.CommandInvokeError: Command 'reiniciar' raised an exception: AttributeError: 'NoneType' object has no attribute 'publish'
aaaaaaaaaaaaaaaaaaaaaaaaa
(((
Sry I'm out of battery
use self.bot.get_emoji instead of the string
ok bro np
emoji = self.bot.get_emoji(986774079191285790)
then
await ctx.guild.delete_emoji(emoji)
that should work
Works Works. Hurrah Hurrah. just one more question. Is it possible to recognize an emoji ID with just a name?
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.
how to pin message
no I don't see it
guess you have to loop through ctx.guild.emojis @slate swan
and check emoji.name for them
!d discord.Message.pin
await pin(*, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Pins the message.
You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to do this in a non-private channel context.
@honest shoal you just do await message.pin()
thanks
It doesn't work for some reason
oh well it's MUCH easier like that
He does not work(
you only have to put an emoji after the command to have an Emoji object
i.e !counter 
you wanna delete the emoji sent?
@app_commands.command(name='unload', description='Disable a command')
@app_commands.describe(command_name="Command Name")
async def unload(self, interaction: discord.Interaction, command_name: str):
if command_name != 'critical':
await self.bot.unload_extension(f'{command_name}')
Command 'unload' raised an exception: AttributeError: 'Main' object has no attribute 'unload_extensions'
Anything obvious I did wrong here?
.counter
And you can not enter emoji.
Discord.py/DB : Hello, is it possible to convert this code into sqlite3 to have a database where all the users + warn and reason can be found ? This is the actual code, I'm available to discuss^^https://paste.pythondiscord.com/dacayocuci
why
your error doesn't match the code...
did you save and restart the bot
oh
aiosqlite, sure
Yea I did
I need to enter a command. emoji were created, sent to the chat and deleted. for profile
Its only 100 lines and its just unload/load/reload commands
I didnt include all of it but it says unload bc thats what I tried doing
do you have a sample just to know how i have to start coding this ?
then somewhere you wrote unload_extensions instead of unload_extension
for some reason, you put an emoji argument in your command
Ooh
remove emoji in
async def counter(self, ctx, emoji)
if you don't want it @slate swan

well, you'll first have to THINK about how you would code it
learn to use SQL, since you'll need it to use CRUD operations
without this argument it gives an error here
that doesn't make sense anyways...
And how can I delete emoji if I only know that the name of the emoji is 321
you can't just get an attribute and call it
you can get the object by name through the discord utils get
for emoji in ctx.guild.emojis:
if emoji.name == "321":
await ctx.guild.delete_emoji(emoji)
that's true
damn
Oh wow, it's still possible. how to write down?
discord.utils.get(iterable, /, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.utils.find "discord.utils.find").
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Changed in version 2.0: The `iterable` parameter is now positional-only.
Changed in version 2.0: The `iterable` parameter supports [asynchronous iterable](https://docs.python.org/3/glossary.html#term-asynchronous-iterable "(in Python v3.10)")s...
emoji = discord.utils.get(ctx.guild.emojis, name="321")
yes
but when you actually use create_emoji before, you already have this Emoji object
and you don't have to use this
Wow works. Thanks a lot. I'll take a look at how discord.utils.get works, otherwise I didn't fully understand it. and thanks everything works!!!!
I hate rewriting my bot π
version control is key
Yea it is
> rewrite bot
+2000000 lines
- 5000000000 lines
Agreed
Can I get ||help for the rewrite||
π€
I made it open sourced because people wanted me to and now rip π
link?
https://github.com/Hunter2809/HunAI
Its nothing but boilerplate as of now
book marked it
thanks
Haha its fine
what bot it is btw?
The AI bot
Using asyncio.create_subprocess_shell to get an async program to run it only prints out the stdout after the program has finished, any way to get live feedback?
imagine using me instesd of self
Totally me
!rule 7
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
what if he is making a shell command?
...
Tbh the help I am gonna be needing with, is the help command cz I hate making those
ic
not sure i havent tried subprocess much
Was replying to Ashley
Wym
designing the embed so it looks good and formatting text in description type of stuff
Ah yea
welp
Thanks.
np
There is a limit of 15 on Option choices right ?
25
Okay, thanks.
Is there any way to overcome that limit though.
Something like a List Builder/ Autocomplete ?
no
It's fine if the user gives some other input than the options, i require something like an autocomplete
u gotta use nested options
I see
there is one i think not sure tho
or add smth like "More options"
π
u could send another message with 25 options
@shrewd apex opinion
Should I send a modal for showing the user information the bot has, or make a paginator?
huh
how does discord.Member as an option work, isn't that kind of a list builder, is it not implementable ?
wdym?
modals
Cool thanks
discord.Member gives a list of all users present in the server as an option, does it not ?
istg if the limit is 25 for TextInput
no it doesn't
What does it do then as a choice
Nice there is a limit of 25 text inputs in a modal
TIL u can also host a discord bot on cloudflare worker
discord is a class Member is an attribute under it so thus discord.Member give an object like class object discord.Member object
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
nice
Yeah, got it.
rip only for js
sed
Lemme confirm
i am gonna use rpi for mine ig
have to make a battery pack tho for it
power cutsβοΈ
Hmm?
two messages in a row each 25 options
@shrewd apex help me make a modal paginator
Im bored entertain me
!ot
Off-topic channel: #ot2-never-nesterβs-nightmare
Please read our off-topic etiquette before participating in conversations.
Yea, u cannot use Python on cf workers π
u mean i click paginator button and it sends next 25 text inputs?
yea smth like that
U click the "Next" button, it shows the next 25 text inputs
i would love to but i am on phone rnπ
I wasn't talking about buttons though, i was talking about a slash command Option with choices
But okay got it
Sad
i have to make a help command for mine as well which i will start tom or day after
that also have a limit of 25 options
π
@shrewd apex wanna see smth cursed?
show
make it 31 for duck's sake
why
options for a whole month
py+js
Yes lol
pys
the def tho
oof
it's not funny it's a global issue
can a modal send a message?
people in africa are suffering because of it
yes i can
How
lmao
No sadly
hmm ic
did you name yourself rip because of this
A modal is just this
no, i had this user for ever
nothing more nothing less
rip
@heady sluice u got a spare bot on yr laptop rn?
hunter can confirm
on my what
computer/laptop
hmm we could try tho it might not work with subclass we could try it in the command like send a modal on button callback from paginator
probably
I need u to test smth π₯Ί
but I've been on phone for 2 weeks
Sad
I'm on vacation
i can test something for u
u got a bot?
π«
yes
Make a command and send a button
until i saw the second sentenceπ
how
I can't say that now
Nice
i don't even know what lib i need for buttons
disnake
rip rip
you don't need any lib
oh, so i can just import discord
you only need discord.com/developers
what for?
yea i did make my own api wrapper
you can implement shit
you can hack discord to implement shit so you can implement shit in your API wrapper
lmao hunter u are better of making it on replit in phone it will get done faster
π
@bot.command()
async def smth(ctx):
v = disnake.ui.View()
btn = Button(text="Test")
v.add_item(btn)
btn.callback = callback
async def callback(inter):
modal = disnake.ui.Modal()
btn = disnake.ui.Button(text="New")
modal.append_component(btn)
btn.callback = cb2
await inter.response.send_modal(modal)
async def cb2(inter):
modal = disnake.ui.Modal()
btn = disnake.ui.Button(text="New")
modal.append_component(btn)
btn.callback = cb2
await inter.response.send_modal(modal)
Looks good?
Nvm, cannot add buttons too, to modals π
Indents are fine tho
ew
Button(text=?
same question ngl
label*
if discordID in [301480016657776642, 464721355116380160]:
a = 0
b = 10
elif discordID in [92786442891169792, 746850928417701990]:
a = 85
b = 99
else:
a = 49
b = 99
Spiking = np.random.randint(a, b)
embed = discord.Embed(title = "STATS", description = Spiking, color = discord.Color.blue())
await ctx.respond(embed=embed)
i was changing my command to give different results for different ids but do i have my if statement incorrect? it only works for the first if and else, not eliuf
Eh, didn't really use the code anyways. Modals can't have buttons
the elif doesnt work cz it doesnt meet the required conditions
wait wym
discordID is never any of those 2 in the lists
can i instead make a nested if statement?
Sure
nested if statement? but why?
if discordID in [301480016657776642, 336895085511835649]:
a = 0
b = 10
else:
if discordID in [92786442891169792, 746850928417701990]:
a = 90
b = 99
else:
a = 45
b = 99
something like this instead?
im just rigging the stat that comes depending on the user
if they are in list one, give them bad stuff, if in list two, give them good stuff, else normal
and that's the reason where inequality starts
a, b = (0, 10) if discordID not in [301480016657776642, 336895085511835649] else ((90, 99) if discordID in [92786442891169792, 746850928417701990] else (45, 99))
``` :3
from re import A
import discord
from discord.ext import commands
import datetime
import asyncio
import random
TOKEN = ""
client = commands.Bot(command_prefix ="!")
@client.command()
@commands.has_role("Developer")
async def gstart(ctx, mins : int, *, prize: str):
embed = discord.Embed(title = "Giveaway!", description = f"{prize}", color = ctx.author.color)
end = datetime.datetime.now() + datetime.timedelta(seconds = mins/60)
embed.add_field(name = "Slutter kl:", value = f"{end}")
embed.set_footer(text = f"Slutter om {mins} minutter!")
my_msg = await ctx.send(embed = embed)
await my_msg.add_reaction(":tada:")
await asyncio.sleep(mins)
new_msg = await ctx.channel.fetch_message(my_msg.id)
users = await new_msg.reactions[0].users().flatten()
users.pop(users.index(client.user))
winner = random.choise(users)
await ctx.send(f"Tillykke! {winner} du vandt {prize}!")
client.run(TOKEN)```
When i start a giveaway it never ends and in the teminal in vscode its writes "Command raised an exception: AttributeError: module 'random' has no attribute 'choise'"
!d random.choice
random.choice(seq)```
Return a random element from the non-empty sequence *seq*. If *seq* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError "IndexError").
l e a r n. t o. s p e l l.
Might not be his main language no need to rub it in.
oh yeah
shit i just saw it now
english is hard so calm down
im calm ;/
English*
no it isn't my main language so sometimes i write a little wrong
what is it about?
Connecting a whole minecraft server to the bot.
How so? Sounds interesting
mhm interesting
!tag
β’
Β» args-kwargs
Β» async-await
Β» blocking
Β» botvar
Β» class
Β» classmethod
Β» codeblock
Β» comparison
Β» contribute
Β» customchecks
Β» customcooldown
Β» customhelp
Β» decorators
Β» defaultdict
cool
Cross commands but more that people can chat in the Minecraft chat and discord chat and allowing them to start/stop/restart the server. It's a private guild/ mc server.
how do i get the help page about how i tag people when discord bot chats?
i wanna try machine learning to make an ai in minecraft idk it sounds fun
Ah, I had that going for one of my old SMPs at one point, there was a plugin where you just put in your discord token and it uses JDA to do a 2 way chat from discord to MC
how do i do that the discord bot tags the person in the text?
Robin, there is no way I'm going to code plugins in java lol
you can string the member
You don't have to code it
the string dunder returns the whole tag of the user
It's already done, and if it's one thing us programmers love, it's work that's already been done by other people
But mine is a bit more custom
understandable. I'm curious, how are you getting it to work so far?
Does Minecraft have some sort of IPC you can hook into?
can you do so that the text that the bot sends is in color?
Lmao no I'm just using sub shell and using stdout and stdin.
ah okay
I mean i probably would've done an approach where I write a quick Java plugin to stream messages to a websocket server in python, handle things from there
I don't think you can do that, I know you can connect a database.
Same but that would require me to code in java
β’
Β» args-kwargs
Β» async-await
Β» blocking
Β» botvar
Β» class
Β» classmethod
Β» codeblock
Β» comparison
Β» contribute
Β» customchecks
Β» customcooldown
Β» customhelp
Β» decorators
Β» defaultdict
#bot-commands please and thank you
If I can achieve it by doing this it would save time and the hassle of searching how to create plugins for 1.6.4 lol
@load.error
async def load_error(self, ctx, error):
if isinstance(error, commands.NoEntryPointError):
await ctx.send(embed=self.error_nosetup_embed)
elif isinstance(error, commands.ExtensionNotLoaded):
await ctx.send(embed=self.error_notloaded_embed)
elif isinstance(error, commands.ExtensionNotFound):
await ctx.send(embed=self.error_nosetup_embed)
else:
raise error
So I'm trying to catch errors w/ slash commands and it doesn't seem to work, it doesn't error (of course) and I think it has to do with the Context.send just because .send doesn't autocomplete which Ive just learned means its probably not going to work
Java πΏ
Ive tried doing it other ways but Im not sure how to basically send the message
await ctx.send(f"Tillykke! @{winner} du vandt giveawayen pΓ₯ {prize}!")```
how do i do that the winner gets tagged?
of a id
so you mean like this?
await ctx.send(f"Tillykke! {winner.mention} du vandt giveawayen pΓ₯ {prize}!")```
keep the {}
{winner.mention}
if it doesn't autocomplete when you type winn then its prob not going to work
assuming youre using vscode like me, pro tip
ye
yes i do
thank you!
client = commands.Bot(command_prefix ="!")
@client.command()
@commands.has_role("Developer")
async def gstart(ctx, mins : int, *, prize: str):
embed = discord.Embed(title = "Giveaway!", description = f"{prize}", color = ctx.author.color)
end = datetime.datetime.now() + datetime.timedelta(seconds = mins/60)
embed.add_field(name = "Slutter kl:", value = f"{end}")
embed.set_footer(text = f"Slutter om {mins} minutter!")
my_msg = await ctx.send(embed = embed)
await my_msg.add_reaction(":tada:")
await asyncio.sleep(mins)
new_msg = await ctx.channel.fetch_message(my_msg.id)
users = await new_msg.reactions[0].users().flatten()
users.pop(users.index(client.user))
winner = random.choice(users)
await ctx.send(f"Tillykke! {winner.mention} du vandt giveawayen pΓ₯ {prize}!")
client.run(TOKEN)```
how could i remove the massage !gstart 10 test
like this
async def gstart(ctx, mins : int, *, prize: str):
delete message
embed = discord.Embed(title = "Giveaway!", description = f"{prize}", color = ctx.author.color)```
?
ctx.message.delete()
thanks
@slate swan do you perhaps know why ctx.send doesn't work here?
maybe its bc im using app_commands but idk
which lib?
discord?
from discord import Guild, Interaction, app_commands
from discord.ext import commands
like this but im using app_commands for slash commands instead of commands
on a side note, it has an Interaction not Context
welcome
I tried that too I did Interaction.response but I just assumed send_message wouldnt work but ill try it
oh wait
I need to change ctx in the function
yes...
it still doesn't remove the message
hard luck
your bot got no perms
at least you understood by yourself :) that's all what matters
:D
I do have another question, when trying to unload extensions it says that they were not loaded which doesn't make sense because I can still use the commands in that file
did you try restarting the bot?
Like just re running it
yeah
ye
Like I load it here in the main file, and I just assume its loaded bc the commands work
@app_commands.command(name='load', description='Enable a command')
@app_commands.describe(command_name="Command name")
async def load(self, interaction: discord.Interaction, command_name: str):
if command_name != 'critical':
await self.bot.load_extension(f'{command_name}')
This is how im basically organizing the commands for it
But it's also a cog
so I dont know if thats why, because when I tried to put it in with the main file it wouldnt work
oh alright
how to send a direct message to an user which is not me trough interaction.response?
nextcord?
pycord
thats prolly not it
ok so you can do it
but not using interaction.response
you can use interaction
interaction.user.send("message")
i think this will work
!pip py-cord
So I changed it to use on_command_error so Im not repeating myself w/ each individual command but its not actually catching anything, idk if maybe I used the wrong @event or something maybe thats different to with slash commands
@app_commands.command(name='reload', description='Reload a command')
@app_commands.describe(command_name="Command name")
async def reload(self, interaction: discord.Interaction, command_name: str):
if command_name in ['all', '*']:
for ext in self.initial_extensions:
await self.bot.unload_extension(ext)
await self.bot.load_extension(ext)
else:
if command_name != 'critical':
await self.bot.unload_extension(f'{command_name}')
await self.bot.load_extension(f'{command_name}')
@commands.Cog.listener()
async def on_command_error(self, interaction: discord.Interaction, error):
if isinstance(error, commands.NoEntryPointError):
await interaction.response.send_message(embed=self.error_nosetup_embed, ephemeral=True)
elif isinstance(error, commands.ExtensionNotLoaded):
await interaction.response.send_message(embed=self.error_notloaded_embed, ephemeral=True)
elif isinstance(error, commands.ExtensionNotFound):
await interaction.response.send_message(embed=self.error_nosetup_embed, ephemeral=True)
else:
await interaction.response.send_message(embed=self.error_failed_embed, ephemeral=True)
print('works')
raise error
what module is ths
discord py?
yes
somebody that have a good website that hoste you'r bot 24/7 free?
I used ctx originally and it didn't work I had to use interactions (I assume because its slash commands and im using app_commands not commands)
so generic resources on the internet aren't as helpful so I basically fix one thing and then someone else doesnt work lol
so you are using other module for slash?
I thought discordpy was still apart of it
Oh but yk what I did have to install something else w/ pip for slash commands
why does my bot alternate being able to @ them and sending this?
async def gstart(ctx, mins : int, *, prize: str):
ctx.message.delete()
embed = discord.Embed(title = "Giveaway!", description = f"{prize}", color = ctx.author.color)```
why doesn't the command !gstart 10 test get removed?
These are the libraries im using
what is message?
when i write !gstart 10 test a giveaway starts and ends in 10 min with the prize "test"
if that what you mean
cause you are removing the message?
AWS has a free tier, CC required. Oracle has a free tier too, CC required + initial fee and refund to see if it's valid
do yk which one has the best uptime
i used heroku but someone told me to use some other one
thanks
Heroku sucks for discord bots, but most reputable cloud service providers will have near 100% uptime
o
They rarely go down and if they do, they'll be back up very fast
Consider many companies small and large rely on them, they need to be very reliable
Would you perhaps know why my @commands.Cog.listener() event isn't catching the errors from the app_commands
is there a different event for that specifically
async def gstart(ctx, mins : int, *, prize: str):
message = "!gstart"
ctx.message.delete()
embed = discord.Embed(title = "Giveaway!", description = f"{prize}", color = ctx.author.color)```
still doesn't remove de message/command
o
You need to pass your app_commands error handler to your commandTree
What is a commandtree
you need to await it
A "tree" that holds all the commands
so would that be the class
I quote it because it's not really a "tree"
In the sense of a binary search tree, for example
and you dont need the message varriable
Pass it where?
Thank you! Know it works! π
He said I need to pass it to the command tree
π
self.bot.tree.on_error = your_error_handler π
I'm not understanding, who said you need to pass what to the command tree?
Okay so ill make the error handler its own thing
You can also subclass
Is that just a class in a class
No, are you familiar with inheritance?
no but I can look it up rq
Obv not, just assign your handler to your tree and it will catches all the errors coming from the app_commands
otherwise you would need a local handler
Personally I find subclassing better because it keeps everything in one place, also more OOP if you get what I'm saying
yup yup
In that case you could just set it up inside your bot's subclass since it contains the three which is equivalent to what i said (Doing self.tree.on_error = ... Instead). I see no point on making a whole new class for that
on_error has () right and requires a error= parameter so I put all_errors like this
bot.tree.on_error(error=all_errors)
Idk if thats right
it takes a discord.Interaction param too
no ? py bot.tree.on_error = all_errors (I suppose that is your errors handler)
Note that your command handler need Interaction and error parameters
Errors handler*
it has to be a normal function
oh alright
and bot.tree.on_error = func_name
You do not need a listener and you overload the function within your cog class not in add_cog method..
I got rid of the listener, not sure what you mean with overloading the function
Oh nvm
I see what youre saying
I thought you were saying add_cog is wrong
it is. You only do self.bot.tree.on_error = self.on_command_error in your def init
new gatewayevents with the automod seems like a cool feature
anyone could help me with sql?
creating models
Imagine OCR programming it for you
A model isn't really something you can "program"
It's more of a layout of how you believe your database should look like
sort of like psuedocode
Though Prisma for example, has their own modelling language
I'm just thinking about plain SQL
CREATE TABLE ...
where you just draw a model with some columns and relationships
the hardest part would be decrypting my handwriting π
hello! I need some help for my discord bot
Having issues with this python bot```py
telnyx lookup
@slash.slash(name="lookup",description="number to lookup",guild_ids=guild_ids)
@commands.has_permissions(administrator=True)
@bot.command(name='lookup', aliases=['pb'])
async def lookup(ctx: SlashContext, phone_number):
try:
await ctx.message.delete()
#async with ctx.typing():
#await asyncio.sleep(1)
i = requests.get(f"https://api.telnyx.com/v2/number_lookup/1{phone_number}")
response = i.json()
embed=discord.Embed(title="Personal Check", description=f"Admin Check" ,color=0x81E15C, timestamp=datetime.utcnow())
embed.set_thumbnail(url="https://www.tillsonburghydro.ca/images/fraud.jpg")
embed.add_field(name="Phone Number:", value=f"{str(response['data']['phone_number'])}", inline=False)
embed.add_field(name="Deep Carrier:", value=f"{str(response['data']['carrier']['name'])}", inline=False)
embed.add_field(name="Country Of Origin", value=f"{str(response['data']['country_code'])}")
embed.add_field(name="Network Node", value=f"{str(response['data']['portability']['ocn'])}", inline=False)
embed.add_field(name="Line", value=f"{str(response['data']['carrier']['type'])}", inline=False)
embed.add_field(name="Note:", value=f"Thank You For The Help!", inline=False)
embed.set_footer(text=f"Resquested By: {ctx.author.name}#{ctx.author.discriminator}", icon_url=ctx.author.avatar_url)
await asyncio.sleep(1)
await ctx.send(embed=embed,delete_after=50)
except Exception as error:
async with ctx.typing():
await asyncio.sleep(4)
embed=discord.Embed(title="Invaild Number Pal!", description=f"{phone_number}", color=0xff0000)
await ctx.send(embed=embed,delete_after=10)
print(i)
mood
Is there any way to access global variables inside async def?
super() is my guess but idk
TypeError: lookup() got an unexpected keyword argument 'kwargs'


