#discord-bots
1 messages Β· Page 187 of 1
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, NoAccountCreatedError):
await ctx.send(embed=...)
# other elif statements for other errors...
else:
# unknown error occurred, print it to terminal
raise error```
oh i forgot () in class definitions is inheritance π€¦ββοΈ
for example: ```py
async def retrieve_account(user_id: int) -> AccountInfo:
info = <query user info>
if info is None:
raise NoAccountCreatedError
return info
@bot.command()
async def my_command(ctx):
info = await retrieve_account(ctx.author.id)
# if the function didn't fail, we can continue normally```
thinking about it i actually would prefer this over the check approach, still removes most of the boilerplate while being flexible and taking advantage of type inference, biggest drawback is now your error handler has to do slightly more work to match that exception
thank you bro you are a wizard π
What's the best way to set variables for each string after a comma? i.e
,hello john, james, jeff
I'd like those names to be they're own variable
use actual command decorator
and not on_message
!d discord.ext.commands.Command
class discord.ext.commands.Command(*args, **kwargs)```
A class that implements the protocol for a bot text command.
These are not created manually, instead they are created via the decorator or functional interface.
I assume you just use .split(",")
why not just use cmd deco and set a param for a list of names?
you mean like?
async def name(ctx, names: list) -> None:
something like that yea
I don't think that's the best way?
If you want commas, use ctx, *, names and .split, if you just want spaces, use ctx, *names
I want commas
first one would be ur best bet theb
Then to save them to there own variable?
oh, it returns a list im dumb
Working on delete message log, but how can I make it so it also detects file attachments such as images, videos, etc.?
@bot.event
async def on_message_delete(message):
if message.author.bot:
return
embed = discord.Embed(description = f"**A message sent by {message.author.mention} has been deleted in <#{message.channel.id}>**\n{message.content}", color = 0xf6ff00, timestamp = discord.utils.utcnow())
embed.set_author(name = f"{message.author.name}#{message.author.discriminator}", icon_url = message.author.avatar)
embed.set_footer(text = f"User ID: {message.author.id} β’ Message ID: {message.id}")
channel = bot.get_channel(1067413418597953637)
await channel.send(embed = embed)```
ModuleNotFoundError: No module named 'discord.ext.menus.views'
anyone know any good open source discored bots I can fork for an all purpous server?
!d discord.Message.attachments
A list of attachments given to a message. If Intents.message_content is not enabled this will always be an empty list unless the bot is mentioned or the message is a direct message.
what are you trying to do?
which discord.ext.menus package are you using?
I don't see a ViewMenuPages there
Do u know which has
who told you to use ViewMenuPages?
they should also know which package they were talking about
@bot.event
async def on_message_delete(message):
if message.author.bot:
return
embed = discord.Embed(description = f"**A message sent by {message.author.mention} has been deleted in <#{message.channel.id}>**\n{message.content}", color = 0xf6ff00, timestamp = discord.utils.utcnow())
if message.attachments:
if len(message.attachments) == 1:
if message.attachments[0].url.endswith(('.jpg', '.png', '.jpeg', '.gif')):
embed.set_image(url = message.attachments[0].url.replace('cdn.discordapp.com', 'media.discordapp.net'))
else:
embed.add_field(name="Attachment", value = message.attachments[0].url)
else:
for message.attachments in message:
embed = discord.Embed(description = f"**A message sent by {message.author.mention} has been deleted in <#{message.channel.id}>**", color = 0xf6ff00, timestamp = discord.utils.utcnow())
embed.set_image(url = message.attachments[0].url.replace('cdn.discordapp.com', 'media.discordapp.net'))
embed.set_author(name = f"{message.author.name}#{message.author.discriminator}", icon_url = message.author.avatar)
embed.set_footer(text = f"User ID: {message.author.id} β’ Message ID: {message.id}")
channel = bot.get_channel(1067413418597953637)
await channel.send(embed = embed)```
Error: `TypeError: 'Message' object is not iterable` on the line `for message.attachments in message:`
How can I fix this
you can't iterate over a message object like the error says
for attachment in message.attachments

da hell did i just read
Just ask
Does anyone know an effective way to promote a discord bot?
okay guys, why my cmd is not recognizing my env
Just loads of bot lists
Perhaps some YT tutorials that have your bot advertised somehow, loads of people watch those tutorials
And try make your bot unique somehow
If you advertise your bot as a moderation bot you're gonna get no servers that way
How to like put in discord embed (description) x(x litteraly has to stay behind number)random number 1-50.random number 1-50
Make a tutorial
show ur actual bot working
Go to reddit
Ask
"Hey guys what shouuld I add to my bot, it has:
x
y
random.randint(a, b)
will give a random int between two vals
Ik that
But didn't work in embed
embed=discord.Embed(title="Crash prediction", description = x (random.randint(1, 101)) . (random.randint(1, 101)), color=00000)
I did it like this
what's x here? a function?
It has to show like x82.81
bruh
No it just has to be behind
you know how a string works, right?
!e ```py
from random import randint
print(f"x{randint(1,100)}.{randint(1,100)}")
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
x14.24
bruh it has to be a swtring
random.randint returns an int
which might be fine normally but if you have an x it doesn't know what to do
Lemme try
do you know what a formatted string is?
Mhm
.
is there any way i can respond to the same interaction multiple times ?
you can defer() an interaction and then use interaction.response.send_message() after deferring it to send multiple
actually you probably don't need to defer it, but for the 2nd message you need to use the function above
i was usint normal commands with ctx before, but recently ive wanted to switch to slash commands, but ive got multiple commands in my bot that send messages repeatedly
for example this one
Hi guys i have connected selenium script to my discord bot, how i can make it that he don't gonna freeze when selenium is doing something?
imma research what defer() is
thanks
Traceback (most recent call last):
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\bot.py", line 742, in _load_from_module_spec
spec.loader.exec_module(lib) # type: ignore
File "<frozen importlib._bootstrap_external>", line 879, in exec_module
File "<frozen importlib._bootstrap_external>", line 1017, in get_code
File "<frozen importlib._bootstrap_external>", line 947, in source_to_code
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\setup_v2\cog.py", line 780
f"> Language {language if language else c.MajaCrossMark}\n\n", colour=c.gold)
^
SyntaxError: f-string expression part cannot include a backslash
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "c:\Discord\Maja Projekt\MajaSystem_Test\bot.py", line 345, in <module>
main()
File "c:\Discord\Maja Projekt\MajaSystem_Test\bot.py", line 58, in main
bot.load_extension(f"modules.{folder}.cog")
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\bot.py", line 864, in load_extension
self._load_from_module_spec(spec, name, extras=extras)
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\bot.py", line 745, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
nextcord.ext.commands.errors.ExtensionFailed: Extension 'modules.setup_v2.cog' raised an error: SyntaxError: f-string expression part cannot include a backslash (cog.py, line 780)
PS C:\Discord\Maja Projekt\MajaSystem_Test> ```
status_embed = nextcord.Embed(title="SETUP β’ Status", description=
f"> Administrator Role {c.MajaCrossMark if admin_role is None else f'{c.MajaCheckMark} \n {get_admin_role.mention}'}\n"
f"> Moderator Role {c.MajaCrossMark if mod_role is None else c.MajaCheckMark}\n" f"> {get_mod_role.mention}\n\n"
f"> Supporter Role {c.MajaCrossMark if sup_role is None else c.MajaCheckMark}\n" f"> {get_sup_role.mention}\n\n"
f"> Log Channel {c.MajaCrossMark if log_channel is None else c.MajaCheckMark}\n" f"> {get_log_channel.mention}\n\n"
f"> Global Channel {c.MajaCrossMark if global_channel is None else c.MajaCheckMark}\n" f"> {get_global_channel.mention}\n\n"
f"> Language {language if language else c.MajaCrossMark}\n\n", colour=c.gold)```
!e ```py
print(f"{'\n'}")
@slate swan :x: Your 3.11 eval job has completed with return code 1.
001 | File "<string>", line 1
002 | print(f"{'\n'}")
003 | ^
004 | SyntaxError: f-string expression part cannot include a backslash
you can't use \n in a f string interpolation
Ok and how can i make it so that i can use it between here:
else f'{c.MajaCheckMark} \n {get_admin_role.mention}'}```
A emoji
yeah then this part is correct
*Custom Emoji
error is coming from a part you use to load the cog
wait
what's line 780 (nvm its from nextcord)
You said i cant use /n in a f string
And i asked how can i do it different
you can't use it in the interpolation
f"hello \n world"
``` will work ```py
a = "hello \n world"
f"{a}"
``` wont
basically you can thave it inside the {}
this is line
f"> Administrator Role {c.MajaCrossMark if admin_role is None else f'{c.MajaCheckMark} \n {get_admin_role.mention}'}\n"```
!e
a = "hello \n world"
print(f"{a}")
@winged coral :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | hello
002 | world
That does work when you're dropping in the variable
oh right
It doesn't work when the backlash is actually inside the curlies
it doesnt work only when it's used there
show the c.MajarCrossMark variable
but that shouldnt be related either
1 min
MajaCrossMark = ""
Is this better? https://paste.pythondiscord.com/uvejaniyod
how do i reply using an interaction ?
smth of the sort interaction.response.reply
also when i do a slash command my bot has this message going for forever it seems like
!d discord.InteractionResponse.send_message
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
if it is discord.py
hm, alright
what abt this ?
if u know
can netlify host discord bots if you connect the files via github?
nope
Why is he not updating the embed
status_embed = nextcord.Embed(title="SETUP β’ Status", description=
f"> Administrator Role {c.MajaCrossMark if admin_role is None else f'{c.MajaCheckMark} {nl} > {get_admin_role}'}\n\n"
f"> Moderator Role {c.MajaCrossMark if mod_role is None else f'{c.MajaCheckMark} {nl} > {get_mod_role}'}\n\n"
f"> Supporter Role {c.MajaCrossMark if sup_role is None else f'{c.MajaCheckMark} {nl} > {get_sup_role}'}\n\n"
f"> Log Channel {c.MajaCrossMark if log_channel is None else f'{c.MajaCheckMark} {nl} > {get_log_channel}'}\n\n"
f"> Global Channel {c.MajaCrossMark if global_channel is None else f'{c.MajaCheckMark} {nl} > {get_global_channel}'}\n\n"
f"> Language {language if language else c.MajaCrossMark}",
colour=c.gold)
embed_start = nextcord.Embed(title="SETUP β’ Start", description="Please wait a moment. Setup begins immediately...", colour=c.blurple)
embed_wait = nextcord.Embed(title="SETUP β’ In progress", description="Please wait a moment. Setup continues...", colour=c.blurple)
respond = await inter.response.send_message(embeds=[status_embed, embed_start])
org = await inter.original_message()
await asyncio.sleep(3)
if admin_role is None:
setup__admin__view_select = setup__admin_role_select(inter)
reply = nextcord.Embed(title="Setup β’ Activate Administrator Role", description=f"{c.MajaSettings} Please select a role.", colour=c.blurple)
await respond.edit(embeds=[status_embed, reply], view=setup__admin__view_select, attachments=[])
setup__admin__view_select.message = org
await setup__admin__view_select.wait()
await respond.edit(embed=status_embed, attachments=[])
await asyncio.sleep(2)
else:
await respond.edit(embeds=[status_embed, embed_wait], attachments=[])
await asyncio.sleep(2)```
Netlify is for static webpages. You don't have a backend, netflify simply serves the relevant HTML from their "backend" which doesn't really do much else
Well you need to reply to the action
(within 3 seconds) or defer it
but ive defered it tho
@client.tree.command()
async def collatz(interaction:discord.Interaction, number:int):
bool_value = False
collatz = list(collatz_func(number))
await interaction.response.defer()
if int(number) == 0:
await interaction.channel.send("Cannot use 0!")
elif int(number) < 0:
await interaction.channel.send("Cannot use negative numbers!")
else:
bool_value = True
for value in collatz[0]:
await interaction.channel.send(f"{value}")
await interaction.channel.send(f"Calculations done: {collatz[1]}")
messy code sorry, made this command like 1 year ago
ive been trying to switch to slash commands recently so its a hassle
Hi are you an helper?
Yes
Can you help with this
in slash context, defer shows up as typing in discord, you need to followup to stop the 'typing' indicator by interaction.followup.send
welcome
Forget it
embed=....,embeds=None,.....
π
Can anyone help with this
namespace = interaction.namespace
embed.add_field(name="Email", value=namespace.get('email', 'Not provided'), inline=True)
embed.add_field(name="Password", value=namespace.get('password', 'Not provided'), inline=True)
embed.add_field(name="Code", value=namespace.get('code', 'Not provided'), inline=True)
``` I tried to listed things from namespace but it not working
Traceback (most recent call last):
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 489, in _run_event
await coro(*args, **kwargs)
File "c:\Discord\Maja Projekt\MajaSystem_Test\bot.py", line 275, in on_application_command_error
raise error
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 888, in invoke_callback_with_hooks
await self(interaction, *args, **kwargs)
File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\setup_v2\cog.py", line 808, in setup_bot
await respond.edit(embed=embed_wait, embeds=None, attachments=[])
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\interactions.py", line 1150, in edit
message = await self._state._interaction.edit_original_message(
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\interactions.py", line 422, in edit_original_message
params = handle_message_parameters(
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\webhook\async_.py", line 488, in handle_message_parameters
raise InvalidArgument("Cannot mix embed and embeds keyword arguments.")
nextcord.errors.InvalidArgument: Cannot mix embed and embeds keyword arguments.```
Use only one embed argument
so i've a list of cogs in a cogs package
and i want to organize them into subpackages & stuff
however, https://stackoverflow.com/questions/48879353 doesn't seem to work
running this gives an empty set
this is my project structure
Whats the best way to make it so that other cant use the command while its running by someone else in the server?
Add a check?
ERROR discord.ext.commands.bot Ignoring exception in command trivia
Traceback (most recent call last):
File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/asyncio/tasks.py", line 456, in wait_for
return fut.result()
asyncio.exceptions.CancelledError
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "main.py", line 229, in trivia
answer_msg = await bot.wait_for('message', check=check, timeout=30)
File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/asyncio/tasks.py", line 458, in wait_for
raise exceptions.TimeoutError() from exc
asyncio.exceptions.TimeoutError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/runner/Agent-Milo/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 275, in trivia
add_user_to_leaderboard(ctx.author.i
can some one help me with this error pls...
Code
Hey @coral mirage!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
!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.
Use this
!paste
Show full error
https://paste.pythondiscord.com/ follow this link
kk
once I enter code what I do?
ERROR discord.ext.commands.bot Ignoring exception in command trivia
Traceback (most recent call last):
File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/asyncio/tasks.py", line 456, in wait_for
return fut.result()
asyncio.exceptions.CancelledError
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "main.py", line 229, in trivia
answer_msg = await bot.wait_for('message', check=check, timeout=30)
File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/asyncio/tasks.py", line 458, in wait_for
raise exceptions.TimeoutError() from exc
asyncio.exceptions.TimeoutError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/runner/Agent-Milo/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 275, in trivia
add_user_to_leaderboard(ctx.author.id, ctx.author.name, -4)
File "main.py", line 202, in add_user_to_leaderboard
cursor.execute(f"INSERT INTO leaderboard VALUES ('{user_id}', '{username}', {score})")
sqlite3.IntegrityError: UNIQUE constraint failed: leaderboard.user_id
The above exception was the direct cause of the following exception:
Okay
Traceback (most recent call last):
File "/home/runner/Agent-Milo/venv/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1349, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/Agent-Milo/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/home/runner/Agent-Milo/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IntegrityError: UNIQUE constraint failed: leaderboard.user_id
Let me tell you whats wrong. So, its a Trivia game, but when times up. It suppose to take points away and let user know times up. But it doesn't It sends me the error instead..
everything else works
which check?
check=check
maybe
Yeah I thought of that, the problem is I don't know any YouTubers and I don't have a popular channel myself
Dude it's one of a kind with features that's aren't in any other bot on discord but for some reason no one cares!
First things first... Don't use sqlite3. Its blocking, meaning the whole code willl stop until the sqlite code has completed its execution. Instead use aiosqlite, or better rapptz-asqlite, they are async. Secondly, don't use f-strings in queries. Use other variables that are specific for different databases. For example, in your case:
cursor.execute(f"INSERT INTO leaderboard VALUES ('{user_id}', '{username}', {score})") #bad
cursor.execute(f"INSERT INTO leaderboard VALUES (?, ?, ?)", (str(user_id), str(username), score)) #good
I'm using replit for this bot.
hmm alright I'll switch to aiosqlite
that would solve my problem ?
It won't really. Its just for optimization purposes
If your bot gets bigger, there's a higher chance of it disconnecting due to these reasons
Is aiosqlite vs asqlite just personal preference when working with Discord bots? I use aiosqlite for my bots and have had 0 issues.
it doesn't get disconnected. Everything works great, It's just that the 30 sec time\s up doesn't send.
Dunno, asqlite is a fork by created by the creator of discord.py. I use asyncpg for my bot anyway
It means, user_id is a primary key and you're inserting a new row containing a user_id that is already in the table
whats the proper code for that ?
or what can I use instead of INSERT
Thanks by the way.
UPDATE?
I need my bot to check if a message contains someone from a json with value "weak"
I have this
narrators.keys() = reliability
for narrator, reliability in narrators.items():
if re.search(narrator, message.content, re.IGNORECASE):
if reliability == "weak":
weak_narrators = [n for n, r in narrators.items() if r == "weak"]
await message.channel.send(f"Weak narrators: {', '.join(weak_narrators)}")```
but when I do !rijal aban, it does nothing
(aban is a item, with val "weak)
I have two warnings, "cannot assign function to call" and "unresolved reference 'reliability"
do you mean reliability = narrators.keys()?
i keep getting ```discord.ext.commands.bot Ignoring exception in command ticket
Traceback (most recent call last):
File "/usr/local/lib/python3.9/dist-packages/discord/ext/commands/core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "/root/roof.py", line 169, in ticket
await ctx.author.add_role(role)
AttributeError: 'Member' object has no attribute 'add_role'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/local/lib/python3.9/dist-packages/discord/ext/commands/bot.py", line 1349, in invoke
await ctx.command.invoke(ctx)
File "/usr/local/lib/python3.9/dist-packages/discord/ext/commands/core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/usr/local/lib/python3.9/dist-packages/discord/ext/commands/core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'add_role'``` with this block of code:
ticket_channels = []
@client.command()
async def ticket(ctx):
channel_name = f"ticket-{ctx.author.name}"
if channel_name in ticket_channels:
await ctx.send("You already have a ticket open.")
return
channel = await ctx.guild.create_text_channel(name=channel_name)
moderator_role = discord.utils.get(ctx.guild.roles, name="Moderator")
await channel.send(f"Welcome to your ticket, {ctx.author.mention}. Please describe your issue thoroughly and a {moderator_role.mention} will be here shortly.")
role = discord.utils.get(ctx.guild.roles, name="Open Ticket")
await ctx.author.add_role(role)
ticket_channels.append(channel_name)
everyone_role = ctx.guild.default_role
await channel.set_permissions(moderator_role, read_messages=True)
await channel.set_permissions(everyone_role, view_channel=False)
# Close ticket
@client.command()
async def ct(ctx):
channel_name = f"ticket-{ctx.author.mention}"
if channel_name not in ticket_channels:
await ctx.send("You don't have a ticket open.")
return
channel = discord.utils.get(ctx.guild.text_channels, name=channel_name)
ticket_channels.remove(channel_name)
role = discord.utils.get(ctx.guild.roles, name="Open Ticket")
await ctx.author.remove_roles(role)
await channel.delete()```
any fixes?
await ctx.author.add_role(role) -> await ctx.author.add_roles(role) , no?
i will try that.
whenever i run the command "ticket" it works but doesnt add the role "Open Ticket"
it will add it then remove it.
how to get the member inviter ?
Alright so i got predictor bot for tower and tower is game where you have β and β so like there is 8 rows of 3 those
Example:
βββ
βββ
βββ
βββ
βββ
βββ
Alright so i want to make star be in random place but only 1 in each row
How to make star be in random place in every row but only 1 star each row
because it's add_roles not add_role
i have tried that it just gives me another error
whats the error?
import discord
from discord import app_commands
from discord.ext import commands
description = '''JungleUpgrades bot to auto claim your order.'''
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix='/', description=description, intents=intents)
@bot.event
async def on_ready():
print(f'Logged in as {bot.user} (ID: {bot.user.id})')
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name="Matki kakieta!"))
print('------')
bot.run('')``` How i can syncing commands to this? ( i have my tree commands in other file )
Why the junk is discord temp banning my bot
It's just a chatbot
@crimson mauve
It's litteraly $hello
$how are you
Etc.
My friend requested that bot
He asked me to make it
It's running on replit
And I checked my terminal
And it says The owner of this website (discord.com) has banned you temporarily from accessing this website.
Alright so i got predictor bot for tower and tower is game where you have β and β so like there is 8 rows of 3 those
Example:
βββ
βββ
βββ
βββ
βββ
βββ
Alright so i want to make star be in random place but only 1 in each row
How to make star be in random place in every row but only 1 star each row
How can I make a bot online always?
I use replit because I can keep it alive
That's more of a general Python-related question than it is specific to Discord bots I think. Though treat the emojis as if they're divided into groups of 3 rather than one large group. You could randomly re-arrange the list [0, 0, 1] for each row and then map the list elements to different emojis.
Purchase a VPS service. I use DigitalOcean for my bots and have had 0 issues so far. You can also host it on your own machine, but you'll need to keep that machine running for as long as you want the bot online.
AWS and GCP have free tiers and you can get GitHub student dev pack if you're a student
You could also consider a one time investment like a raspi. But the silicon crisis made those kinda expensive last i checked
I didn't understand anything but anyways i sent it here bc it's for embed
Google it, it gives you access to many resources for free if you are a student
Also why is replit banning my bot
Just that bot
I made lots of bots
And replit is banning just that bot
Someone else is using your replit
Something something shared IPs
Maybe because it's called chopper and it has a profile picture like that anime character
I don't watch anime btw
No lol
Click on this tag
So it's not that copyright thingy
Bot is offline
Because if enough people login from the same IP to discord theyβll flag it
Seems sorta sus
Weirdddd
My bot has some stuff that is incredibly intensive for processing XD
Imagine seeing 40 bots login from same IP in 5 minutes
Youβd thjnk it is sus
Fr
Well you'll need to pay then, good hardware isn't free
Yeah I was thinking I can rent out a consumer GPU
Or multiple
Like 4090s
Because replit uses the same machine for multiple repls, so it's easy to get ratelimited
And then maybe have my discord bot connect with an API to them
Oh
But idk how smart that is seems not very secure XD
Or just blocked because itβs hella mad sus
I made many bots in replit
And all of them are running with no errors now
All of them are online
Just that chopper is banned
Yeah that seems about right
Itβs probably hit or miss af
But this is not even first time
Itβs probably based on volume and demand
If a lot of people need the service more likely to be limited
I even made multiple files in replit for same bot
And reseted token
And runned it
It was online for like a day or two
And then it gets banned
And I can't turn it on ever again
there isn't anything you can do about it
Yeah
imagine one computer making thousands of requests to the discord api
that'/s what I said
imagine 50 bots logging in from same api very quickly
from discord pov its very suspicouis
Oh no
I remember
Few weeks ago in another server there was one kid
Who was ratelimiting one specific channel somehow
But how?
Messages were sending sooo slowly
It took like 15+ seconds to send a message
They called that kid "coke"
So coke was using one script to rate limit a discord channel
General chat
He was trolling is
Us*
But how did he do that?
This is off-topic at this point
yeah
@naive briar do you watch adventure time a lot?
Well I asking that here because some people from that server had a theory that coke is using a self bot
o yeah u can do that
discord doesn't rlly care
Self bots are still discord bots I guess
I grew up with it
I was considering making one to answer discord programming questions
So I am in right channel
they're not allowed and considered spam
I know
do u have thories on the great mushroom war
How is that relevant to anything
But how can a self bot
Rate limit a channel?
Without sending any messages, reacting, editing or something like that
spam packet
or like
tpyingh not typing typing rlly fast might work idk
Then prob didn't ratelimit channel
They did
probs a conincidence
I doubt it
even if they did it's not uncommon to see script kiddies do stuff like that
Server owner made a temp general
Where chat was normal and fast
And people were sending screenshots where it says "this channel is write rate limited"
And some administrators who are programmers too
Said that kid rate limited a channel
like you can crash other peoples discord clients with a image
Yeah
so it wouldn't be very suprising
or u used to ccrash their comp
Image loggers?
cuz discord would freeze
I dont think so,idk though bc the one im referring to has been patched since like 2020
These script kiddies probably just download scripts from github
idk most just copy the image url
nah im not rlly interested in this
not really
"pls click link pls click link pls click link omg pls click link"
plus im busy
They can crash your computer and account
required hardware accleration
only worked on windows
Ok
only worked on desktop version of windows
required hardware acceleration to be on
could be fixed by going onto browser version and closing channel
smth annoying was GC spamming
bc yoiu could get 200,000 group chats in 20 seconds and it would make discord unusable
Oh
So there is literally a whole documentation lol
"How to get scammed by skids and destroy your PC"
yeah itβs so hard
Yeah
Hello guys I have in my cog a error handler which is:
@sbx.error
async def solebox_error(self, interaction: discord.Interaction, error):
if isinstance(error, discord.app_commands.errors.MissingRole):
embed = discord.Embed(
title="Only Admins are allowed to use this command",
color=int("0x5057b5", 16)
)
await interaction.response.send_message(embed=embed, ephemeral=True)
else:
raise error
How do i make a cog with this error handler but that will works for all my others cogs and not only the one that is in the same cog that where the error handler is
Unknown to script kiddies they normally make a issue very apparent which means that people that would actually know how to cause a lot of harm with it don't get to
True
Script kiddies are like cancer in my opinion
Everyone listen
If you are a script kiddie
Please don't be that
You are not harming others, you are just harming yourself.
I mean look at you
You are probably thinking something like "hehehe, I am 1337 hacker, this guy is so dumb"
Just stop doing that
It's bad for you
I mean I don't rlly care abt them
It's just mostly people who haven't gotten into programming yet and are like 12-14
Β―_(γ)_/Β―
Yeah
But they are annoying
class form(ui.Modal,title='Ticket'):
test1=ui.TextInput(label='form1',placeholder='form1_placeholder',style=discord.TextStyle.short,required=True)
test2=ui.TextInput(label='form2',style=discord.TextStyle.short,required=True)
async def on_submit(self,interaction: discord.Interaction):
payment = self.payment.value
pur = self.pur.value
user_name = interaction.user
channel_name = f"ticket-{user_name}"
category = interaction.guild.get_channel(1068970627291152394)
channel = await interaction.guild.create_text_channel(channel_name, category=category)
overwrite = discord.PermissionOverwrite(read_messages=True, send_messages=True)
await channel.set_permissions(interaction.user, overwrite=overwrite)
await channel.send(f"test: **{test1}** \nBuying? **{test2}**")
await channel.send(f'@{user_name}, @verbal kraken',delete_after=1)
await interaction.response.send_message(f'Made ticket. **{channel}**',ephemeral=True)
class Menu(discord.ui.View):
def __init__(self):
super().__init__()
self.value = None
@discord.ui.button(label='Make Ticket!', style=discord.ButtonStyle.grey)
async def ticket(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_modal(form())
@bot.command()
async def ticket(ctx):
view = Menu()
embed=discord.Embed(color=0x212121)
embed.set_image(url='https://cdn.discordapp.com/attachments/972084009762967604/972465729087635506/pfps-57cXSR.gif')
await ctx.send(embed=embed)
embed=discord.Embed(title="Click me to make a ticket", description=f"Test ticket emebed", color=0x212121)
await ctx.send(embed=embed,view=view)
Idk whats wrong with this code but my tickets like seem to work then after a while it just fails and sends a This interaction failed in discord
Theres no traceback logs of it at all
prob ur bot disconnecting
do u have an error handler?
nah i don't i guess i could add one , i don't see any disconnect logs tho
i mean if u have an error handler that would be the reason no traceback logs
but if you dont have one do you have logging at least?
yeah i got logging
and it doesn't show anything in console?
can you show me ur recent logs before it stopped working
yeah nothing at all even when i press the ticket
[2023-01-28 18:40:57] [INFO ] discord.client: logging in using static token
[2023-01-28 18:40:57] [INFO ] discord.gateway: Shard ID None has connected to Gateway (Session ID: d1a264e94bcf0318de453b2515444b16).
thats it
that's all that shows?
yeah no errors at all
Try setting logging level to DEBUG
^
it'll flood you with information but it's helpful at least
alr
yeah kinda really no information to go off rn most i can think of is hosting issue or bot just disconnecting and never reconnecting
set logging level to debug , still no logs
error happened around ~6 mins without no use
discord.py ghosts errors in views ( and maybe modals too), you'll have to setup a seperate error handler for that
!d discord.ui.View.on_error
await on_error(interaction, error, item, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A callback that is called when an itemβs callback or [`interaction_check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View.interaction_check "discord.ui.View.interaction_check") fails with an error.
The default implementation logs to the library logger.
how do i take a list of users as an argument?
does this work w/ slash commands?
not sure
i haven't used slash commands
i would guess yes, but there is probably a built-in way to do it
it doesn't
you'll have to make your own transformer
!d discord.app_commands.Transformer
class discord.app_commands.Transformer```
The base class that allows a type annotation in an application command parameter to map into a [`AppCommandOptionType`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.AppCommandOptionType "discord.AppCommandOptionType") and transform the raw value into one from this type.
This class is customisable through the overriding of methods and properties in the class and by using it as the second type parameter of the [`Transform`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Transform "discord.app_commands.Transform") class. For example, to convert a string into a custom pair type:
i'm surprised that the discord api doesn't have a built in way to take a list of users
class Sys(commands.Cog, name="sys"):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
self.background_task.start()
@tasks.loop(seconds=10.0)
async def background_task(self):
global _today
refresh = _today != dt.date.today()
# some more stuff
for some reason background_task isn't running
does anyone know why?
Any errors?
no errors
i put prints in the bkg task function and they just don't print
so i should put them here:
async def setup(bot: commands.Bot):
await bot.add_cog(Sys(bot))
```?
If you're adding the cog, then yes
But the task is still expecting to be starting in an async function
for some reason,
@tasks.loop(seconds=1.0)
async def background_task():
global _today
refresh = _today != dt.date.today()
print("did this get called")
async def setup(bot: commands.Bot):
await bot.add_cog(Sys(bot))
background_task.start()
this doesn't work
examples/background_task.py lines 13 to 25
async def setup_hook(self) -> None:
# start the task to run in the background
self.my_background_task.start()
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')
@tasks.loop(seconds=60) # task runs every 60 seconds
async def my_background_task(self):
channel = self.get_channel(1234567) # channel ID goes here
self.counter += 1
await channel.send(self.counter)```

Do you guys know if it is possible to code a discord both using python? I know its not conventional, but is it possible?
https://github.com/Rapptz/discord.py
knock yourself out
Pretty conventional if you ask me
Oh that's fantastic, thanks
Thanks! I'm fairly new to python, lol
Considering discord.py and discord.js are the two most used libraries when it comes to making discord bots
Ah I see, thx, I've only heard of js for some reason
cuz djs is the most commonly used one
Because all loves javascript and as well as infinite possibilities :)
Impossible
can somebody help me? why it tolds me this
impossible
!e
print("bla bla"/2)
Nvm xd
xd?
Well so the vc.play thingy accepts str, bytes like obj or pathlike obj, e.g..../user/music/blabla.mp4, but m_url is a dict
So u need to extract the informations from the dict
thank u bro
XD
!rule
The rules and guidelines that apply to this community can be found on our rules page. We expect all members of the community to have read and understood these.
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTubeβs robots.txt file; (b) with YouTubeβs prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
I was about to ping you

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
....gey bot
Is there a way to have a discord.Attachment class inside a typing.Union style converter? Like an advanced version of typing.Union that takes the attachment class?
Example:
attachment: typing.Union[discord.Attachment, str]
Or would I have to use a custom converter?
Anyone know how I could implement some sort of autocomplete feature? Eg a search command that seaches a dict. So if you were to type son but the dict had song, it'd still send the closest matching in the dict
,search song
apparently the built-in discord.Attachment converter isnt implemented like a normal converter so that syntax doesnt actually work as expected... yeah, a custom converter or some function will have to do
Kk, thanks
you're looking for either fuzzy matching (e.g. the packages thefuzz and rapidfuzz), or a full-text search engine if you need it to scale, or a basic hand-made implementation with in membership testing / str.startswith()
I'm trying fuzzywuzzy and it seems even with a threshold it always finds one ?
why discord just do that and not make any noise in voice channel
prob doing wrong i use thefuzz to return a list of options that is bigger than 25 with autocomplete and it works fine
Wait, i have to write voice.is_playing() after voice.play()?
How do I find who invited the bot after a bot joins a server?
!d discord.Guild.audit_logs
async for ... in audit_logs(*, limit=100, before=..., after=..., oldest_first=..., user=..., action=...)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") that enables receiving the guildβs audit logs.
You must have [`view_audit_log`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.view_audit_log "discord.Permissions.view_audit_log") to do this.
Examples
Getting the first 100 entries:
```py
async for entry in guild.audit_logs(limit=100):
print(f'{entry.user} did {entry.action} to {entry.target}')
```...
@shrewd fjord sorry question how link button "ButtonStyle"?
example: "@discord.ui.button(label="View Giveaway", emoji="π", style=discord.ButtonStyle.url, url="https://google.com")"
hmm
how to get message interaction after bot restart?
button=discord.ui.Button(......,style=......)
view=ButtonClass()
view.add_item(button)
For url, u dont need a callback xd
Hmmm
!d discord.ButtonStyle.url
Nop look...
;-;?
async def button2(self,interaction: discord.Interaction, Button: discord.ui.Button):
await interaction.response.send_message("Sorry, not available working soon.", ephemeral=True) ```

there think no work click button error link
Add it normally...
Like this
yeah but is:
How r u sending the view?
yeah link view
;-;
-_-
same code
;-;
..
Dont u have slash command or prefix?
slash command
Show that code
...
;-;
have full much code gW
no cant but ya ya already button there
and no working button link.
said error.
just send this
await send_message(....view=??)
yes "message = await giveaway_channel.send(msg, embed=embed, view=ViewButton())"
good boy
view=ViewButton().add_item(discord.ui.Button(label=...,emoji=....,style=....url=....))```
;-;?
confuse 
Just change the view kwarg
yes "message = await giveaway_channel.send(msg, embed=embed, view=ViewButton())"
To this
yes "message = await giveaway_channel.send(msg, embed=embed, **
view=ViewButton().add_item(discord.ui.Button(label=...,emoji=....,style=....url=....)))**"
hmmm
Nahh
nop no cant.
ya have already theree code button.
wtf
;-;?????
"class ViewButton(discord.ui.View):"
am i looking at
Literally screen
@view=ViewButton()..... ???????????????????
Xd
yes but confuse, no is incorreect.
Just do what i did
that is so far from being correct lol
This

@shrewd fjordremember before there is:
there participants button and other is link button.
._.
...
,,,
Do this
>:{
sigh.. try.
this is wrong
exactly
Tell the right
he has it right

Bro, he is trying to add url kwarg on normal button
Cant u check?
because that is above is a button and but it was not below message button, why does it participate when link button? is that wrong?
..
So now tell i am right or 
do
self.add_item(discord.ui.BUtton(label="...", url="")
Both works πΏ
hmm
Button*
is " async def button2"?
remove the second button and add what i just sent
no
No callbacks for url buttons
π ?
remove ur second button and add exactly what i typed
sigho k try.
i can't believe you sent this
Hehe boi
Both works so y not add the view on command π
Me not able to understand english πΏ
If u trying this:
...
which? think message?
class ViewButton(discord.ui.View):
def __init__(self):
super().__init__()
#first button here.....
self.add_item(discord.ui.Button(label='Click Here', url=url))
This type of links
First button under super? ππ
yes is super lol.
like actually
do u even read docs or look at examples?
or u just spit shit out ur ass
fix ur indentation but yes
maybe?
!mute 983274033770557460 1d Please re-read our #code-of-conduct before participating in our server any further.
:incoming_envelope: :ok_hand: applied mute to @slate swan until <t:1675065851:f> (1 day).
@shrewd fjord no problem okay my sleep!
Picbot
?
Y u being rude lmao? But try mine code too. Both works bruh
Danggg mods are too fast
!d discord.ui.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.
!d discord.SelectOption
class discord.SelectOption(*, label, value=..., description=None, emoji=None, default=False)```
Represents a select menuβs option.
These can be created by users.
New in version 2.0.
Why is he not updating the embed
status_embed = nextcord.Embed(title="SETUP β’ Status", description=
f"> Administrator Role {c.MajaCrossMark if admin_role is None else f'{c.MajaCheckMark} {nl} > {get_admin_role}'}\n\n"
f"> Moderator Role {c.MajaCrossMark if mod_role is None else f'{c.MajaCheckMark} {nl} > {get_mod_role}'}\n\n"
f"> Supporter Role {c.MajaCrossMark if sup_role is None else f'{c.MajaCheckMark} {nl} > {get_sup_role}'}\n\n"
f"> Log Channel {c.MajaCrossMark if log_channel is None else f'{c.MajaCheckMark} {nl} > {get_log_channel}'}\n\n"
f"> Global Channel {c.MajaCrossMark if global_channel is None else f'{c.MajaCheckMark} {nl} > {get_global_channel}'}\n\n"
f"> Language {language if language else c.MajaCrossMark}",
colour=c.gold)
embed_start = nextcord.Embed(title="SETUP β’ Start", description="Please wait a moment. Setup begins immediately...", colour=c.blurple)
embed_wait = nextcord.Embed(title="SETUP β’ In progress", description="Please wait a moment. Setup continues...", colour=c.blurple)
respond = await inter.response.send_message(embeds=[status_embed, embed_start])
org = await inter.original_message()
await asyncio.sleep(3)
if admin_role is None:
setup__admin__view_select = setup__admin_role_select(inter)
reply = nextcord.Embed(title="Setup β’ Activate Administrator Role", description=f"{c.MajaSettings} Please select a role.", colour=c.blurple)
await respond.edit(embeds=[status_embed, reply], view=setup__admin__view_select, attachments=[])
setup__admin__view_select.message = org
await setup__admin__view_select.wait()
await respond.edit(embed=status_embed, attachments=[])
await asyncio.sleep(2)
else:
await respond.edit(embeds=[status_embed, embed_wait], attachments=[])
await asyncio.sleep(2)```
!d discord.InteractionResponse.send_message - the method doesn't return the sent message
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.

So?
You can't edit it like that
Use edit_original_response
!d discord.Interaction.edit_original_response
await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the original interaction response message.
This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit "discord.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if the message sent was ephemeral.
*nextcord
i posted a discord.py post having trouble with asyncio or threading
Dont work
After I have selected the Administrator Role, the Administrator Role should be checked because it is no longer none
If I run the command again, the embed is correct
@naive briar
Myes jay should've been more friendly
how can i create channels with slash commands? ive been reading the docs and i cant find anything regarding a way to create actual channels
!d discord.Guild.create_text_channel doesn't matter if you do it with slash commands or smth else
await create_text_channel(name, *, reason=None, category=None, news=False, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=..., default_auto_archive_duration=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel "discord.TextChannel") for the guild.
Note that you must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") to create the channel.
The `overwrites` parameter can be used to create a βsecretβ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.11)") of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite") as the value.
Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
Of course I can help but you didn't even say what you need help with π
whats the issue u have got
show us some of the code that u think gives an error
Traceback first please, it will be easier to find out where the problem is
np
π€
@vale wing am i the only one confused
@slate swan aga ne hatasΔ± veriyo amk
Confused by what
by exenifix and oppenheimer
!rule language
4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.
i mean oppenheimer posted code and deleted it after like 2 seconds
Hello i have a problem, i want to avaible a command with another command for a especific time any one knows how to do it?
I asked you to send traceback like twice
I will say yusuf
They posted something like system32 deleter
And I didn't really say "thanks"
yea it was smth with os and looked quite malicious tbh
no no not u, lytsh thanked oppenheimer for that malicious code
@slate swan please send traceback you get here
thats what it looked like
Yeah stuff like that happens regularly π
why is this chat so chaotic π is it like that here 24/7?
The what
no
!code can you put it into here
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.
π
Then asher came and sent us a banana
@vale wing i think they are just trolling u
!code
totally
!code can you put it into here print("sa")
nothing beats depression better than a banana
!code print("sa beyler")
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.
They are trolling each other, unsure how they are trolling me
Let him have it
im helped you

That's how society works
please unblock me
to me it seems like oppen and lytsh know each other and they jus trollin, they have the same language in their bios so i assume

kek indeed
just state ur problem ignore him as simple as that
@slate swan please unblock me
cd Desktop/Programlar/Yusuf/yusufaatcagΔ±mvirΓΌs.py π π
hi, why this code doesnt work?
class automsg(commands.Cog):
def __init__(self, bot):
self.bot=bot
@commands.Cog.listener()
async def on_message(self, message):
liste = ("Bonjour", "bonjour", "Bonsoir", "bonsoir")
nombre_mention=len(message.mentions)
if nombre_mention== 0 and message.content.startswith(liste):
await message.channel.send (f"Salut {message.author.mention} ")
if nombre_mention >= 1 and message.content.startswith(liste):
await message.channel.send (f"Salut" + ",".join([mention.mention for mention in message.mentions]))
Because variables are named in spanish
what?
he is joking lol
@slate swan say it
give us the error u have got
!py help
why are people just.. "hello, this doesnt work, fix it"
provide us with the error u have got at least
Sorry I didn't know startswith can accept an iterable
!d str.startswith
str.startswith(prefix[, start[, end]])```
Return `True` if string starts with the *prefix*, otherwise return `False`. *prefix* can also be a tuple of prefixes to look for. With optional *start*, test string beginning at that position. With optional *end*, stop comparing string at that position.
me
i dont have any error... and bot bot have 0 reaction when i write the words in liste
No documentation found for the requested symbol.
lol is trash
i mean a string is a iterable
Guys can you not cause chaos or we will have to call mods
any(message.content.startswith(i) for i in liste)
Do you have message content intent enabled
hi guys
@slate swan unblock me im sorry abaut this
assuming u also have cog loaded properly and intents as well
!e py print("abcde".startswith(("L", "D", "abc")))
@vale wing :white_check_mark: Your 3.11 eval job has completed with return code 0.
True
@shrewd apex this is what I meant
I didn't know about this myself π
what do you mean? i dont understand, sorry
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
yes
import discord
from discord.ext import commands
import os
from dotenv import load_dotenv
intents = discord.Intents.all()
bot = commands.Bot (command_prefix="!", intents=intents)
all intents are here! π
cog loaded properly?
yes
also do u have another on_message event somewhere?
yes and it work fine
Listener or event
listener
Ye that shouldn't cause issues
does the event in the cog get triggred?
i have a problem, i want to avaible a command with another command for a especific time any one knows how to do it?
can u add a print statement and check?
Btw pretty sure you don't need to check for amount of mentions, if you join a sequence of 1 element it will be just 1 element
for the 2nd on_message?
yeah
Command cooldown or what
please 2secons, i paste my code
but how?
I meant "do you mean command cooldown"
I try to use after_invoke
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
@commands.cooldown(1, 180.0, commands.BucketType.guild)??
Yes?
@vale wing
What are you trying to achieve @lunar kayak
That isn't how you do extensions
just avaible a command with another command... i want use this for a registration @vale wing
Bot is defined once and then is parsed into cogs upon extension load
What the
What does "avaible" mean
I am pretty sure such word does not exist in english
available*
Well still the sentence doesn't make much sentence to me cause it's not a verb
??
If you speak foreign language please use translator to describe what you are trying to achieve
French, right?
yes
you too?
I try to temporarily enable a command with another command @vale wing
Now this makes more sense
qu'est-ce que tu veux faire avec: "https://pastebin.com/0GtFpgWe"
a little
- Make a list/set that contains user IDs
- When command that enables another command is used, add user ID to the list
- In target command check if user is in the list
- Once target command is done, remove user from list, you can use after_invoke hook for that
Thanks a lot
He wants the bot to react with the words that are in the tuple without having to type the prefix
He has no error in the trackback...
Yeah and that's because of improper cog loading
You have to do it like this
# main.py
class Bot(commands.Bot):
async def setup_hook(self):
await self.load_extension("ext.sample")
bot = Bot(...)
bot.run(...)
# ext/sample.py
class MyCog(commands.Cog):
...
async def setup(bot):
await bot.add_cog(MyCog(bot))```
my main.ppy is this:
import discord
from discord.ext import commands
from cogcmd.cog_info import cog_info
from cogcmd.cog_cmd import liste_commandes
from cogcmd.monde import monde
from cogcmd.automsg import automsg
import os
from dotenv import load_dotenv
intents = discord.Intents.all()
bot = commands.Bot (command_prefix="!", help_command=None, intents=intents)
load_dotenv()
TOKEN = os.getenv("TOKEN")
@bot.event
async def on_ready():
print("Le bot est connectΓ©")
await bot.load_extension("cogcmd.cog_info")
await bot.load_extension("cogcmd.monde")
await bot.load_extension("cogcmd.cog_cmd")
await bot.load_extension("cogcmd.automsg")
bot.run(TOKEN)
I hate this so I do autosetup https://github.com/BobuxBot/BobuxAdmin/blob/master/utils/bot.py#L62-L72
utils/bot.py lines 62 to 72
def auto_setup(self, module_name: str) -> None:
module = importlib.import_module(module_name, None)
sys.modules[module_name] = module
members = inspect.getmembers(
module,
lambda x: inspect.isclass(x) and issubclass(x, commands.Cog) and x.__name__ != "Cog",
)
for member in members:
self.add_cog(member[1](self))
self.log.ok("%s loaded", module_name)```
lambda xD
Lambda is just a function
What is the error to start with
He does not have errors, but isn't getting any response, so something has must be wrong
Did he make extension and load it properly
@vale wing the second part of my code it works fine, look :
the cogs work fine...
its very strange...
Is it the same cog
on_message_2?
Edit one so it looks like this
@commands.Cog.listener("on_message")
async def whatever_cool_name(...)```
Yo
Hello spooky
Hewo exen 
Guys, I wanted to make that when a specific word or emoji is in a message, to be stored by my bot, and when I request a specific command to give me the storaged messages.
Anyone knows how can I start?
@commands.Cog.listener("on_message")
on_message is not defined
π§
check if that emoji or word on message's content or not
If there store the line in a file
You sure you put quotes around
How can you even recommend that
π
Use database
Sqlite3?
Can someone help?
Yes it's fine for your case
Actually you're partially right because sqlite database is a file
LOL hahaha I will start, thx guys
I was a txt user
Bro i legit made birthday command with using txt file π
really?
Yea lmfao
My format was
birthdate
member_id
birthdate
member_id
Xd, the i check it with enumerate and match up those lines
I never was txt user. I was pickle user π
π₯ ZAMNNN
And then was like "why tf is my data corrupt"
bruh lmao
Ur pickle isnt strong enough 
It's good in terms of objects serialisation
Because he does not have one
ππππππ
Imagine having a real pickle
Exenifix: 
Weird context
facts
Pretty weird
Who started?
Not me 

:-:
help plss
Someone help please?
I want to get optional variables using slash commands in my discord bot, how do I do it? I am using the discord.py library
screenshot full window
You should create a .env file
So you put your token there, and use the prefix TOKEN in the actual code
And yeah don't name functions in russian
If you want it to be named like that just do
@bot.command(name="Π»ΠΎΠ°Π΄")
async def load(...)```
where can i set required False or True for options
because ik with pycord u can do ,required=True or False
def setup(bot):
bot.add_cog(test(bot))
only like that
Someone know how to connect discord bot to mongodb ?
i j shifted to cogs is there any thing as command.Cog.user?
there is ctx.author
nevermind figured it out ty
is there a way to override a global error handler with a local one?
is the best way just to check in the global error handler if the name is the command i want to override, and to not do it if it is?
you can use the motor library
!pypi motor
async for log in channel.guild.audit_logs(limit=1):
if log.action == discord.AuditLogAction.webhook_create:
await log.target.delete()
'Object' object has no attribute 'delete'```
ποΈ something not right here
what is an "Object" object?
webhook
@bot.listen()
async def on_webhooks_update(channel):
async for log in channel.guild.audit_logs(limit=1):
guild = channel.guild
if log.action == discord.AuditLogAction.webhook_create:
euser = await audit_user(guild, discord.AuditLogAction.webhook_create)
if not euser.id == 1064491535086931998:
try:
await euser.user.ban(reason="PM-Beta: (ΠΠ½ΡΠΈ ΠΊΡΠ°Ρ)Π‘ΠΎΠ·Π΄Π°Π½ΠΈΠ΅ Π²Π΅Π±Ρ
ΡΠΊΠΎΠ²")
except:
pass
try:
await log.target.delete(reason="PM-Beta: (ΠΠ½ΡΠΈ ΠΊΡΠ°Ρ)Π‘ΠΎΠ·Π΄Π°Π½ΠΈΠ΅ Π²Π΅Π±Ρ
ΡΠΊΠΎΠ²")
except Exception as e:
print(e)```
Can somebody help me with this? my bot doesnt make any noise in the voice channel, just this, there is my code
@torn sailyea but its not working at all , i got all links in code , but still not connecting
class MyBot(commands.Bot(command_prefix="-"))
will this work?
i wanna use commands.Bot inside mybot
would be great if you could tell me a solution
learn inheritance
have u installed discord.py with voice support ie u need pynacl
hey everyone !
i have something to ask
im using pillow to add text to an image but the text is not in the right place
I made a small drawing to explain where I want the text ^^
pls send code thx
@bot.command()
async def say(ctx, *, text: str):
background = Image.open("sayempty.png")
draw = ImageDraw.Draw(background)
font = ImageFont.truetype("supercell-magic.ttf", 48)
text_width, text_height = draw.textsize(text, font)
while text_width > 500 or text_height > 200:
font = ImageFont.truetype("supercell-magic.ttf", font.size - 1)
text_width, text_height = draw.textsize(text, font)
draw.text((int((700 - text_width) / 2), int((250 + text_height) / 2)), text, (0, 0, 0), font=font)
buffer = io.BytesIO()
background.save(buffer, format="PNG")
buffer.seek(0)
file = discord.File(fp=buffer, filename=f"{text}.png")
await ctx.send(file=file)```
so?
whats this error mean
make sure you reset your token because its leaked in that screenshot
are you using pythonanywhere?
not sure whats causing it though, might be related to your service provider
Might you be on MacOS by chance?
anyone have an idea ?
Traceback (most recent call last):
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 489, in _run_event
await coro(*args, **kwargs)
File "c:\Discord\Maja Projekt\MajaSystem_Test\bot.py", line 275, in on_application_command_error
raise error
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 888, in invoke_callback_with_hooks
await self(interaction, *args, **kwargs)
File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\setup_v2\cog.py", line 858, in setup_bot
await org.edit(embeds=[status_embed, reply], view=setup__language__view_select, attachments=[])
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\interactions.py", line 1150, in edit
message = await self._state._interaction.edit_original_message(
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\interactions.py", line 422, in edit_original_message
params = handle_message_parameters(
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\webhook\async_.py", line 515, in handle_message_parameters
payload["components"] = view.to_components()
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\view.py", line 204, in to_components
children = [item.to_component_dict() for item in group]
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\view.py", line 204, in <listcomp>
children = [item.to_component_dict() for item in group]
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\select\base.py", line 194, in to_component_dict
return self._underlying.to_dict()
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\components.py", line 295, in to_dict
"options": [op.to_dict() for op in self.options],
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\components.py", line 295, in <listcomp>
"options": [op.to_dict() for op in self.options],
AttributeError: 'str' object has no attribute 'to_dict'```
where does the error come from?
looks like one of your select options was a string and not a SelectOption instance
I see
In components.0.components.0.options.0.emoji.name: Invalid emoji
In components.0.components.0.options.1.emoji.name: Invalid emoji```
These are just normal emojis
πΊπΈ and π©πͺ
can you show the code
flag_us = ":flag_us:"
flag_de = ":flag_de:"```
standard emojis need to be written in code with their unicode equivalents because discord's API doesnt actually recognize the text :flag_us:, thats something unique to their desktop application
!charinfo πΊπΈπ©πͺ
\U0001f1fa: REGIONAL INDICATOR SYMBOL LETTER U - πΊ
\U0001f1f8: REGIONAL INDICATOR SYMBOL LETTER S - πΈ
\U0001f1e9: REGIONAL INDICATOR SYMBOL LETTER D - π©
\U0001f1ea: REGIONAL INDICATOR SYMBOL LETTER E - πͺ
\U0001f1fa\U0001f1f8\U0001f1e9\U0001f1ea
Hello I am creating a bot to receive notifications from discord when a vinted article is published. I hosted it on a hosting site and the problem is that my bot uses the authentication cookie from a vinted computer. The question I ask myself is how can I open a link from a bot so that the cookie is created on my machine. I don't know if I was very clear thanks in advance
So?
you'd therefore either write flag_us = "\U0001f1fa\U0001f1f8" and flag_de = "\U0001f1e9\U0001f1ea" respectively
How shoul it looks like?
Oh okay thanks
@hushed galleon can you help me with another problem
help me please, my discord bot just do this and doesnt play sound
FFMPEG is closing just 1 second after connecting
Are you sure you're sending it the stream?
Good evening,
It's been a long time since I programmed discord bot.
And when I am trying to see what's in the message send by a user with the function : if message.content.lower() == something
the bool object is never true even thaugh something is egal to the message send
@bot.event
async def on_message(message):
print("Message")
if message.content.lower() == "/Helpy":
usage = """
devine -> dΓ©marre le jeu
stop -> arrΓͺte le jeu
"""
await message.channel.send(usage)
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
without the message content intent message.content will always be "" (an empty string)
Hey, do you know how i can make the user select 1 item from 3 different options in an argument
It pops up and gives them their options when they click on the argument in the slash cmd
Wym
Unless the bot was pinged then the message content will be given
Right
I'm kinda confused. You mean like they have to choose a kwarg??
It sounds like you can just parse 1 argument for their choice
i want the user to be able to choose 1 of the four(day, week, month, year)
Hey can you maybe help,
why does it raise an error when i try and edit the variable msg
it says msg is nonetype
Can we see the traceback?
send_message() doesnt return a message, so you'd have to use original_message() afterwards
I have a question, the discord.FFmpegPCM must have the executable parameter?
gah i keep forgetting its original_response
i have a bunch of background task functions that i wanna load
however, from playing around, it seems that only loading them in setup_hook works
where should i store the bkg functions? if i put them in a cog, it won't have a setup functions & i'll see an error each time i start the bot
How do i use original_message
oh right, if its just to edit the message then you can use edit_original_response()
!d discord.Interaction.edit_original_response
await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the original interaction response message.
This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit "discord.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if the message sent was ephemeral.
e.g. py await interaction.response.send_message("Hello...") await interaction.edit_original_response(content="world!")
thank you very much
xd
#python-discussion if small or #βο½how-to-get-help
π apppreciate it
!d discord.FFmpegPCMAudio
class discord.FFmpegPCMAudio(source, *, executable='ffmpeg', pipe=False, stderr=None, before_options=None, options=None)```
An audio source from FFmpeg (or AVConv).
This launches a sub-process to a specific input file given.
Warning
You must have the ffmpeg or avconv executable in your path environment variable in order for this to work.
by background tasks are you referring to @task.loop()s? its fine to write them inside cogs
if i put them inside setup() they don't seem to run
lemme try again
@tasks.loop(seconds=1)
async def asdf():
print("was this called")
async def setup(bot: commands.Bot):
await bot.add_cog(Sys(bot))
asdf.start()
```yeah, this doesn't work
works fine for me ```py
@tasks.loop(seconds=5)
async def my_loop():
print("hello world!")
async def setup(bot):
my_loop.start()
2023-01-29 18:06:36 INFO discord.client logging in using static token
hello world!
2023-01-29 18:06:37 INFO discord.gateway Shard ID None has connected to Gateway ...
hello world!
hello world!```
oh i thought you said you had an error on startup
event loop could be blocked, or extension wasnt actually loaded?
Loaded extension 'cogs.management.sys'
```the extension was definitely loaded
i put a print inside `setup()` as well and that one printed
we'll have to see some code I'd say
you're definitely not telling us something we should see
what do you wanna see?
https://paste.pythondiscord.com/ditujajeve the main code is here
https://paste.pythondiscord.com/awizolowex the cog code is here
tell me if you need anything else
first thing I can note
on_message seems redundant
you shouldn't sync in on_ready
but that's besides your current issue
only does that if i tell it too (rn it's set to false)
still, that's not where you want it to be
could you put your task inside your cog?
you can just start it inside the init
optionally, you can add a before_loop in that task which waits for the bot to be ready before running
@your_sexy_task.before_loop
async def your_sexy_task_before(self):
await self.bot.wait_until_ready()```
class Sys(commands.Cog, name="sys"):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
self.counter = 0
self.asdf.start()
@commands.command()
async def count_command(self, ctx):
await ctx.send(f"Here's your count {self.counter}")
# same function stuff here
@tasks.loop(seconds=5)
async def asdf(self):
self.counter += 1
async def setup(bot: commands.Bot):
await bot.add_cog(Sys(bot))```
can you try this?
just use the count_command and check if it changes after like 10 seconds to something else but 0
damn
we'll just start using best practices and go on from there
async def setup_hook(self):
await self.load_extension("cog_ext")```
use this to load your extensions, so add that in your subclassed bot and remove the asyncio.run(....) you're doing above bot.run(...)
Tasks are expected to be starting in a async function



?