#discord-bots
1 messages ยท Page 294 of 1
Here's the check part of it
def check(msg):
if isinstance(context, discord.Interaction):
print(context.message.id, msg.id)
if context.message.id != msg.id:
return True
if context.message.id != msg.id:
return True
The second part works, (the part that handles regular commands) but the slash command version isn't working because a message doesn't exist at the time of the purge
could just use before kwargs of channel.purge and then use interaction.id, it would fetch messages before the interaction command
I'll try that now
@naive briar still doesnt work 
Your code
Yeah, why do we even have this channel if discord.py server exist
class CreateSelect(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.select(
custom_id="guide",
options=[
discord.SelectOption(label = 'What is Sampler', emoji = 'U+2728'),
discord.SelectOption(label = 'Guide to AI Models', emoji = 'U+1F4DA'),
],
)```
uhhh?
I was there before, but they don't really help with support any time i ever asked so I just left xD
make help posts. either me or someone else will. i read pretty much all of the help posts there
๐ :books:
try to use this maybe?
I'll think about rejoining at some point, too lazy tonight lol
hm unicode character for emoji?
ok then
yeah.... cause ๐โจ is also giving me error
alright
like the ones from ?charinfo
wdym?
!charinfo ๐บ
\U0001f63a: SMILING CAT FACE WITH OPEN MOUTH - ๐บ
so... which one do i use?
\U0001f4da - books
\U00002728 - sparkles
also need to construct an discord.PartialEmoji() for those
so it works?
why does it not wonna work like my other code ๐ญ
it does
alright... will do
so basically what this means is that within your emoji kwarg (for example the first one), it will be emoji=discord.PartialEmoji(name=\U00002728)
Do you get the error when running the code?
uh you dont need to, it accepts str as well
but why not for me ?
no....
!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.
.from_str also but doesn't work for unicode emojis (aka the default ones)
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
๐บ
gonna have to whip out jsk
can someone help me or no
explain
you are going to have to explain what are you trying to do
my command does not work like at all i get no error
you should
it should log it if you have logging set up
Show your current code then ๐คท
If they override the on_message without processing the commands, it won't
from discord.ext import commands, tasks
import asyncio
intents = discord.Intents.default()
intents.message_content = True
intents.messages = True
intents.members = True
# Initialize bot with command prefix '!'
bot = commands.Bot(command_prefix='!', intents=intents)
BOT_PREFIX = '!'
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name} - {bot.user.id}')
print('------')
watching_activity = discord.Activity(type=discord.ActivityType.watching, name="over AutoShop")
await bot.change_presence(activity=watching_activity)
@bot.command()
async def purchase(ctx):
# Replace these placeholders with your actual PayPal and crypto wallet addresses
paypal_address = "**[PayPal](https://www.paypal.me/erfanproguy2)**"
bitcoin_wallet = '**bc1q5cf7v6lr7yrtdferlqq07hqww7wqw8dfwp5a66**'
litecoin_wallet = '**Laf9AR7LdtrpkrTgFkx5RVci65ngxViTqa**'
ethereum_wallet = '**0x3f74a98bA3468e25F9cFc02852BF7883B4D707e9**'
embed = discord.Embed(title="Purchase Information", description="Here are the following purchase options:", color=0x00ff00)
embed.add_field(name=" Paypal", value=paypal_address, inline=False)
embed.add_field(name=" Bitcoin Wallet", value=bitcoin_wallet, inline=False)
embed.add_field(name=" Litecoin Wallet", value=litecoin_wallet, inline=False)
embed.add_field(name=" Ethereum Wallet", value=ethereum_wallet, inline=False)
await ctx.send(embed=embed)
@bot.event
async def on_message(message):
if bot.user.mentioned_in(message):
# Respond with the bot's prefix
await message.channel.send(f"My prefix is `{BOT_PREFIX}`")
bot.run('')```
it was working earlier even when i didnt process ;-;
why you on_message to begin with?
sounds like a scam bot
Did you remove the process_commands?
just shut it down at this rate
how? do you not see my code.
What's wrong with overriding it?
for commands
It is
How?
no i meant you dont need to instantiate PartialEmoji since the kwarg accept direct str
I mean, that's also how discord.py its process commands ๐คท
ah i see. thanks for clearing that up
prefixed comamnds process that way
Yes?
nonetheless, just set the command_prefix to have the command.when_mention func to process mentions
They are apparently want to tell the prefix to the user when they mentioned the bot
you guys can't understand what the on_message code even does with op
What do you mean?
anyways, op never even mentioned the error
There are no errors, only that the bot doesn't process the commands
oh my processing was still in my if statement
works now ๐
thank you catlover
and noelle
ok
Finally got it working, had to do an entire workaround with it deferring then then checking whether or not it was responded to alreaady or not (so to know whether to use .followup.send() or .response.send_message()
Anyways, thank you for the assistance anyway, I really appreciate it!
!d discord.Embed
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if itโs within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
x == y Checks if two embeds are equal.
New in version 2.0...
how do you send a path thingy to a channel, eg #discord-bots through the bot
!d discord.TextChannel.mention
property mention```
The string that allows you to mention the channel.
howโd you send it
๐คท
await ctx.send(content=channel.mention)
Just as a reference, all interactions can only be used once. For sending followups, use interaction.followup, which returns discord.Webhook
channel.send
Get channel, check if isinstance(channel, TextChannel), use send
The isinstance check is to make sure pyright doesn't throw errors
How I can get role name by ID?
!d discord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
Changed in version 2.0: `role_id` parameter is now positional-only.
@commands.has_permissions(ban_members=True)
async def unban(ctx, *, member_id):
try:
banned_users = await ctx.guild.bans()
member_id = int(member_id)
banned_user = discord.utils.find(lambda ban: ban.user.id == member_id, banned_users)
if banned_user:
await ctx.guild.unban(banned_user.user)
embed = discord.Embed(
title="User Unbanned",
description=f"User ID {member_id} has been unbanned by {ctx.author.mention}.",
color=discord.Color.green()
)
await ctx.send(embed=embed)
else:
embed = discord.Embed(
title="Unban Error",
description=f"User ID {member_id} is not currently banned.",
color=discord.Color.red()
)
await ctx.send(embed=embed)
except ValueError:
embed = discord.Embed(
title="Unban Error",
description="Invalid member ID provided.",
color=discord.Color.red()
)
await ctx.send(embed=embed)
except discord.Forbidden:
embed = discord.Embed(
title="Unban Error",
description="I don't have the necessary permissions to unban members.",
color=discord.Color.red()
)
await ctx.send(embed=embed)
Why doesnt this unban command work?
what doesn't work about it, please describe it
doesnt unban or input any embeds/error handling at all
(also no erros in terminal)
my code:
@bot.hybrid_command(name="imagine-guide")
async def ticket(ctx):
embed = discord.Embed(title = "> Guide to AI Models", color = 0x714fff)
embed.set_author(name = "Guide to Using the Image Generation System:")
embed.description = "To make it easier to use the image generation system, we've created a handy guide to help you get started with this. This comprehensive guide provides detailed information about each AI Model and Sampler used in the Imagine system to give you a clear understanding of everything."
await ctx.send(embed, view=CreateSelect())```
and the output which comes:
like this is amusing me 
is the command even get called? can you put a print in it to make sure?
you need to pass it to embed kwarg
!d discord.ext.commands.Context.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.
This works similarly to [`send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send) for non-interaction contexts.
For interaction based contexts this does one of the following...
embed ^
ohhhhhh
thanks
and where exactly would i put a print
just in your command function, anywhere at the top
@commands.has_permissions(ban_members=True)
async def unban(ctx, *, member_id):
try:
banned_users = await ctx.guild.bans()
member_id = int(member_id)
banned_user = None
print("Command loaded")
for ban_entry in banned_users:
user = ban_entry.user
if user.id == member_id:
banned_user = user
break
if banned_user:
await ctx.guild.unban(banned_user)
embed = discord.Embed(
title="User Unbanned",
description=f"User ID {member_id} has been unbanned by {ctx.author.mention}.",
color=discord.Color.green()
)
await ctx.send(embed=embed)
else:
embed = discord.Embed(
title="Unban Error",
description=f"User ID {member_id} is not currently banned.",
color=discord.Color.red()
)
await ctx.send(embed=embed)
except ValueError:
embed = discord.Embed(
title="Unban Error",
description="Invalid member ID provided.",
color=discord.Color.red()
)
await ctx.send(embed=embed)
except discord.Forbidden:
embed = discord.Embed(
title="Unban Error",
description="I don't have the necessary permissions to unban members.",
color=discord.Color.red()
)
await ctx.send(embed=embed)```
never printed
do you have message content intents enabled?
yes
do you have an error handler?
show it
async def ban_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
embed = discord.Embed(
title="Missing Argument",
description="Please specify the user to ban.",
color=discord.Color.red()
)
await ctx.send(embed=embed)
elif isinstance(error, commands.BadArgument):
embed = discord.Embed(
title="User Not Found",
description="The specified user was not found.",
color=discord.Color.red()
)
await ctx.send(embed=embed)
elif isinstance(error, commands.CheckFailure):
embed = discord.Embed(
title="Permission Error",
description="You don't have permission to use this command.",
color=discord.Color.red()
)
await ctx.send(embed=embed)```
can you re-raise it? just do at the bottom of the if-elif chain ```py
else:
raise
raise error would work wouldnt it
it would
like this? idk what you mean
where did you re raise it though?
lmao they showed the wrong error handler
but they have to do that for each anyways
oh wait yeah
could've just let the global error handler see it
in your unban_error, just do ```py
if isinstance(...):
...
else:
raise
A hands-on guide to Discord.py
https://fallendeity.github.io/discord.py-masterclass/error-handling/#global-handler this is how to set up global error handler if you wish
oh okay i fixed it should i be all good now?
!e ```py
if False:
a = 10
else:
print(a)
@slate swan :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 4, in <module>
003 | print(a)
004 | ^
005 | NameError: name 'a' is not defined
idk i dont see what you changed
it's a chained error anyways so
now you need to apply this logic to each error handler you have
!e ```py
def div():
return 1 / 0
def handle(err):
raise
try:
div()
except Exception as e:
handle(e)
@slate swan :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 10, in <module>
003 | handle(e)
004 | File "/home/main.py", line 8, in <module>
005 | div()
006 | File "/home/main.py", line 2, in div
007 | return 1 / 0
008 | ~~^~~
009 | ZeroDivisionError: division by zero
yep
any errors if you invoke this? there could be multiple things tbh
i mean yes
TypeError: object async_generator can't be used in 'await' expression
use async for instead
!d discord.Guild.bans
async for ... in bans(*, limit=1000, before=..., after=...)```
Retrieves an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator) of the users that are banned from the guild as a [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry).
You must have [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members) to get this information.
Changed in version 2.0: Due to a breaking change in Discordโs API, this now returns a paginated iterator instead of a list.
Examples
Usage...
what?.
when you go to the docs page you can see an example
it changed from a list to an async iterator because of a breaking change..
Hello,
Have any good tutorial how to make a different folder like "commands" and my main.py identify this folder and register the commands?
I'm having alot of problems like
discord.ext.commands.errors.CommandNotFound: Command "addpergunta" is not found
Interesting that they didn't even put load_extension there.
Ah, they did
https://gist.github.com/15696/a1b10f044fbd658ce76ab1f862a1bda2
like this, but setup and load_extension are async now
it says invalid syntax....
oh...
id really recommend understanding how decorators work because of how extensively used they are in discord.py
3 words:
" my stupid brain "
A decorator is a function that modifies another function.
Consider the following example of a timer decorator:
>>> import time
>>> def timer(f):
... def inner(*args, **kwargs):
... start = time.time()
... result = f(*args, **kwargs)
... print('Time elapsed:', time.time() - start)
... return result
... return inner
...
>>> @timer
... def slow(delay=1):
... time.sleep(delay)
... return 'Finished!'
...
>>> print(slow())
Time elapsed: 1.0011568069458008
Finished!
>>> print(slow(3))
Time elapsed: 3.000307321548462
Finished!
More information:
โข Corey Schafer's video on decorators
โข Real python article
Heyo ppl, I'm looking for some assistance in getting this damn bot to send alerts
@slate swan me? Intents are set
showing your code would be helpful
Show your code and explain what's going wrong
We are not magicians ๐คทโโ๏ธ
โข Ask your Python question, not if you can ask or if there's an expert who can help.
โข Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
โข Explain what you expect to happen and what actually happens.
Did you set it in the code?
The Discord gateway only dispatches events you subscribe to, which you can configure by using "intents."
The message content intent is what determines if an app will receive the actual content of newly created messages. Without this intent, discord.py won't be able to detect prefix commands, so prefix commands won't respond.
Privileged intents, such as message content, have to be explicitly enabled from the Discord Developer Portal in addition to being enabled in the code:
intents = discord.Intents.default() # create a default Intents instance
intents.message_content = True # enable message content intents
bot = commands.Bot(command_prefix="!", intents=intents) # actually pass it into the constructor
For more information on intents, see /tag intents. If prefix commands are still not working, see /tag on-message-event.

too flippin long
!paste
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
well i don't need a users message
how else will your command work
its not meant to be interactive, simply fetch data from the api and send the alert @vocal snow
You have a command start_alerts
How you want it to be triggered, if you can't access the messages?
holy shit
so the start_alerts command is not meant to be used
im gonna go hide in the corner now
happens to the best of us
intents = discord.Intents.default()
intents.members = True
intents.messages = True
messages is already included in default
you want message_content
!mcintent
The Discord gateway only dispatches events you subscribe to, which you can configure by using "intents."
The message content intent is what determines if an app will receive the actual content of newly created messages. Without this intent, discord.py won't be able to detect prefix commands, so prefix commands won't respond.
Privileged intents, such as message content, have to be explicitly enabled from the Discord Developer Portal in addition to being enabled in the code:
intents = discord.Intents.default() # create a default Intents instance
intents.message_content = True # enable message content intents
bot = commands.Bot(command_prefix="!", intents=intents) # actually pass it into the constructor
For more information on intents, see /tag intents. If prefix commands are still not working, see /tag on-message-event.
@bot.command()
async def start_alerts(ctx):
await ctx.send(f"Alerts started with message: {message_content}")
better?
and from where you get the message_content varriable here?
nope
wtf
also you did show your token
awesome
and the message_content is not enabled still
intents.message_content = True # enable message content intents
intents.overnight_billionare = True
welp that was a quick server kill
can someone help in #1145712633220177980
Why is that?
It means you can't have capital letters
I making transcript and i have a question
How i sand smth like message auhtor name: 'text'
now i have smth like this
i need
msg auhtor name : 1
Hi?
Can you create something in python that takes people's tokens
python can?
import discord
TOKEN = "TOKEN"
client = discord.Client()
@client.event
async def on_ready():
print("RUNNING")
@client.event
async def on_message(message):
channel = client.get_channel(818202447067480084)
if message.channel.id == channel.id:
if (message.author.bot) or (message.content) == '-clear':
return
embed = embed_for_user(message.author)
if'\n'in message.content:embed.add_field(name=message.content.split('\n')[0],value=''.join(message.content.split('\n')[1:]))
else:embed.description=message.content
embed.color = 0xdd4c59
embed.timestamp = __import__('datetime').datetime.utcnow() # UTC better
embed.set_footer(text="Instagram", icon_url="https://images-ext-1.discordapp.net/external/4386b73r8DPwBkrBH6gPpeIFvxsg-yZjz3DFXSq-cLg/https/images-ext-2.discordapp.net/external/C6jCIKlXguRhfmSp6USkbWsS11fnsbBgMXiclR2R4ps/https/www.instagram.com/static/images/ico/favicon-192.png/68d99ba29cc8.png")
send_extras = {}
if message.attachments:
file = await message.attachments[0].to_file()
file.filename = file.filename.replace("_", "")
embed.set_image(url=f"attachment://{file.filename}")
send_extras['file'] = file
await channel.send(embed=embed, **send_extras)
await message.delete()
def embed_for_user(user):
embed = discord.Embed()
embed.set_author(name=f"{user.name}", icon_url= user.avatar_url)
return embed
client.run(TOKEN)
print(client.user.name)
D:\pythonProject\Scripts\python.exe C:/Users/pirat/PycharmProjects/pythonProject/main.py
Traceback (most recent call last):
File "C:/Users/pirat/PycharmProjects/pythonProject/main.py", line 3, in <module>
client = discord.Client()
TypeError: __init__() missing 1 required keyword-only argument: 'intents'
Process finished with exit code 1
!intents
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.
where is the error
client = discord.Client()
TypeError: init() missing 1 required keyword-only argument: 'intents'
read this ^
create Intents instance and pass it to Client
it was working last year is is a copy paste past code
can you help me with it?
but there was a change in the library
everything is explained here #discord-bots message
just instead of commands.Bot you have discord.Client
Why not work?
import time
import random
payload = {
'content': (['Hi','by'])
}```
@slate swan 
import discord
from discord import Intents
TOKEN = "token"
intents = Intents.default()
intents.message_content = True
client = discord.Client(command_prefix="!", intents=intents)
@client.event
async def on_ready():
print("RUNNING")
@client.event
async def on_message(message):
channel = client.get_channel(1145730366963990619)
if message.channel.id == channel.id:
if (message.author.bot) or (message.content) == '-clear':
return
embed = embed_for_user(message.author)
if'\n'in message.content:embed.add_field(name=message.content.split('\n')[0],value=''.join(message.content.split('\n')[1:]))
else:embed.description=message.content
embed.color = 0xdd4c59
embed.timestamp = __import__('datetime').datetime.utcnow() # UTC better
embed.set_footer(text="Instagram", icon_url="https://images-ext-1.discordapp.net/external/4386b73r8DPwBkrBH6gPpeIFvxsg-yZjz3DFXSq-cLg/https/images-ext-2.discordapp.net/external/C6jCIKlXguRhfmSp6USkbWsS11fnsbBgMXiclR2R4ps/https/www.instagram.com/static/images/ico/favicon-192.png/68d99ba29cc8.png")
send_extras = {}
if message.attachments:
file = await message.attachments[0].to_file()
file.filename = file.filename.replace("_", "")
embed.set_image(url=f"attachment://{file.filename}")
send_extras['file'] = file
await channel.send(embed=embed, **send_extras)
await message.delete()
def embed_for_user(user):
embed = discord.Embed()
embed.set_author(name=f"{user.name}", icon_url= user.avatar_url)
return embed
client.run(TOKEN)
print(client.user.name)
[2023-08-28 17:46:59] [ERROR ] discord.client: Ignoring exception in on_message
Traceback (most recent call last):
File "D:\pythonProject\lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "C:/Users/pirat/PycharmProjects/pythonProject/main.py", line 17, in on_message
embed = embed_for_user(message.author)
File "C:/Users/pirat/PycharmProjects/pythonProject/main.py", line 33, in embed_for_user
embed.set_author(name=f"{user.name}", icon_url= user.avatar_url)
AttributeError: 'Member' object has no attribute 'avatar_url'
anyone can help me?????////
now whats the problem
yeah this is another thing that has changed its .avatar.url now
๐
instead of?
error?
instead of .avatar_url
!e ```py
import random
payload = {
'content': (['Hi','by'])
}
random.choice(payload)
@slate swan :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 8, in <module>
003 | random.choice(payload)
004 | File "/usr/local/lib/python3.11/random.py", line 374, in choice
005 | return seq[self._randbelow(len(seq))]
006 | ~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^
007 | KeyError: 0
random.choice takes list not dictionary
then you did something wrong
!e ```py
import random
x = [1, 2 ,3 , 4, 5]
print(random.choice(x))
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
2
code
^^
except if you have all keys from 0 to len(dict) inside that
payload is a dict
ty
- full traceback
- It tells you what's wrong
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
Don't ask for help with such things here please
how can i start a code getting source from html site( its my first time trying to white pythong with html)
Request the website
how
!d aiohttp
Aiohttp aiohttp
Honestly we need to get R. Danny in here for the tags
Promoting Dannyware
Ideally what you will want to do is to instantiate your ClientSession obj when the bots starts up
Good example of this
What could be the reason that my bot doesn't respond to commands?
Message intents idk
it has all the intents, so I assume it also has message intents
Show code
import os
import random
import requests
import discord
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv("DISCORD_BOT_TOKEN")
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='/', intents=intents)
bot.remove_command('help')
API_response = requests.get("https://api.earthmc.net/v2/aurora/towns/Atlanta/").json()
print(API_response)
@bot.command()
async def help(ctx):
embed = discord.Embed(
title='Help section',
description='Welcome to the help section',
colour=discord.Colour.brand_green()
)
await ctx.send(embed=embed)
@bot.event
async def on_ready():
messages = [f'Logged in as {bot.user.name}', f'{bot.user.name} is ready to work', f'{bot.user.name} is alive', f'{bot.user.name} is ready to help']
await bot.get_channel(1145525565043003462).send(random.choice(messages))
@bot.event
async def on_message(message):
# Check if the message is not from the bot
if message.author.bot:
return
user_message = message.content.lower()
response = ''
if user_message[0] == '/':
return
if user_message in ['hey', 'hello', 'hi']:
response = f'Hello, {message.author}'
await message.channel.send(response)
def run_discord_bot():
bot.run(TOKEN)
You know there is something called commands.HelpCommand right
no, it's my first time coding a discord bot
class MyHelpCommand(commands.MinimalHelpCommand):
def get_command_signature(self, command):
return '{0.clean_prefix}{1.qualified_name} {1.signature}'.format(self, command)
class MyCog(commands.Cog):
def __init__(self, bot):
self._original_help_command = bot.help_command
bot.help_command = MyHelpCommand()
bot.help_command.cog = self
def cog_unload(self):
self.bot.help_command = self._original_help_command```
See the documentation: <https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#help-commands> for more details.
For migrating from old helpformatters: <https://discordpy.readthedocs.io/en/latest/migrating.html#helpformatter-and-help-command-changes>
A walkthrough on subclassing help:
<https://gist.github.com/InterStella0/b78488fb28cadf279dfd3164b9f0cf96>
thx
np
The reason why your bot is not listening for the help command is that you pretty much effectively removed it
oh, okay
Wdym by non-blocking, just asking
What does โblockingโ mean?
https://discordpy.readthedocs.io/en/latest/faq.html#what-does-blocking-mean
Ty
By using something like requests, you essentially block your whole entire bot event loop
Which renders your whole entire bot useless while processing the http requests (w/ requests)
So itโs a different loop
Yes
No it just straight up blocks it. I would recommend learning how asyncio works to get an better understanding
np
so, it should make it much faster if I can request multiple API's at the same time with aiohttp?
Well yes. I recommend not calling multiple apis at once since you probably will get rate limited
Nah, it's created after deletion (But subclassing is a better way)
And the reason is on_message
Does that happen before the bot.command?
What happen?
Hey guys,
In need of some assistance if anyone can answer.
I have some code thatโs throwing a recursion error however itโs only when I run it on this on pc. When I run it on any other computer it runs perfectly fine so I don't believe its a code issue as it should hypothetically be doing the same thing on my other pc. However on my other computer the code runs and does as its supposed to no problem.
I've searched the history of recursion error in this guild but wasn't able to find anyone with a similar problem and most of google says it has to do with the code. But again works fine on another pc
Last night I uninstalled python and it fixed it for like 35 minutes. Then started spamming the error in the console. But I've had said code running for 5+ hours on other pc with no issues
Show code ๐คทโโ๏ธ
Though it looks it's not related to the discord bots, will be better to use channel like #1035199133436354600 or #algos-and-data-structs
It is in a discord bot.
Unfortuantely its 3k+ lines ( has a bunch of functions and requests being made ) and it doesn't specify where the error is from. I have added some debug prints but they aren't showing much either
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
thanks. Ill continue browsing and see as the issue isn't the code but more of a computer thing so maybe your right and I should bring it to #1035199133436354600
doesn't specify where the error is
do you have an error handler?
Are you printing exception objects?
If you get recursion error you get traceback and it accurately shows where the error is coming from
Please show traceback
But for it to show the error on one pc and not the other?
You cannot guarantee it's device-dependent, I suspect it's random
So can you show traceback?
Yeah ill have to send over when I get back on pc just stepped out
Idk its just strange it only gives recursion on one pc and not the other as I have had it running on my other pc for 5+ hours without any issues but the second I plop the code back on main pc it spits recursion errors
I remember one guy being absolutely sure that adding a print() into his code that does API requests fixes error caused by something above that print
Your case might be similar to this
hmm
Ran it again and got
Maximum recursion depth exceeded while calling a python object | Function: GetProxy
GetProxy code:
def getproxy():
try:
with open("Data/proxies.txt", "r") as file:
proxies = file.read().splitlines()
proxy = random.choice(proxies)
return {'http': f'http://{proxy}', 'https': f'http://{proxy}'}
except Exception as e:
print(f"{str(e).capitalize()} | Function: GetProxy, Retrying", False)
pass
Not full traceback
oh dammit it didn't copy
Raise the exception instead of printing it
And not full code definitely since you don't call the function from itself hence there's no recursion
And the output from here would be
Maximum recursion depth exceeded while calling a python object | Function: GetProxy, Retrying False
not just
Maximum recursion depth exceeded while calling a python object | Function: GetProxy
Indeed
Most likely many functions and other stuff named getproxy causing confusion
That's why shouldn't have everything in one file
!e ```py
def x():
x()
x()```
@slate swan :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 4, in <module>
003 | x()
004 | File "/home/main.py", line 2, in x
005 | x()
006 | File "/home/main.py", line 2, in x
007 | x()
008 | File "/home/main.py", line 2, in x
009 | x()
010 | [Previous line repeated 996 more times]
011 | RecursionError: maximum recursion depth exceeded
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/NK7TEF7T4H6IAEPKXJXGCRPWH4
Error: Name "Get" is not defined
No, the error is lying to you
Well Get isn't in your code
Share the full traceback
Did you import get from discord.utils?
no..
ill see if it worked
yea functions dont spawn randomly you need to import them
tis is why the dpy server is superior
How is that
Can't say without getting muted
it seems that when i put whatevery i need to put in my status it applies my role but when I remove it it doesnt remove like its supposed to
Share your code
Isn't presence update a different event or it was changed
!d discord.on_presence_update
discord.on_presence_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) updates their presence.
This is called when one or more of the following things change:
โข status
โข activity
This requires [`Intents.presences`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.presences) and [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members) to be enabled...
!d discord.on_member_update
discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) updates their profile.
This is called when one or more of the following things change...
Not a valid event for presence update from what I can see
@carmine pilot you're listening to wrong event
so nothing i can do now?
Just change on_member_update to on_presence_update
Hi, I cant get this simple thing to work. Is something wrong with this lines? The bot will not answer
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('!test'):
await message.channel.send('Ok!')
Do you have your event decorator?
still doesn't remove the role, only applies it
Share your code
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.
Okay so you don't have an event decorator...
I dont know what that is. So I guess no. I guess I have to google it
...
i found my last error thanks for helping tho :)!!!
!paste
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
Hi does someone want to review my cog?
https://github.com/No767/Kumiko/blob/dev/Bot/Cogs/config.py
Here are some background knowledge that you are going to need:
-
Redis is used within my bot as a fast caching layer for server configurations. Since all server configs are stored within my PostgreSQL server, it would be faster to get it from Redis than making expensive db calls for static config values. Although LRU caches can be used or even a simple dict cache, I wish not to increase any memory usage as I want my bot to be as light as possible
-
all feature checks first check the value from Redis, and if not found, makes or updates the cache with said value and gets it from the db instead (this is the primary redis why Redis is used in the first place)
-
utils for this cogs can be found under
Libs.cog_utils.config, UI components can be found underLibs.ui.config
help
im figuring it out hold on bbg
async def join(interaction: Interaction):
"""Join the voice channel the user is in"""
if interaction.user.voice:
channel = interaction.user.voice.channel
await channel.connect()
else:
await interaction.response.send_message("not in a voice channel")
print(f"vc: {interaction.user.voice}")```
so the code, says if im in a vc, it says None, even though i am in a vc. This is an issue as it cannot tell that i am currently in a voice channel that the bot has full access to whenever it should return the voice channel im in
example:
What intents do you have?
intents.typing = True
intents.presences = True
client = discord.Client(intents=intents)
client = run(intents=Intents.all())
def __init__(self, *, intents: Intents):
super().__init__(intents=intents)
self.tree = app_commands.CommandTree(self)
async def setup_hook(self) -> None:
await self.tree.sync()```
ok guys!
thank you for sending this
i love you so very much, just realized one of my intents was client = run(intents=Intents.None())
not all of us make mistakes like this only the ones who dont know wtf their doing ๐ฏ
Trust me everyone has mistakes like this.
Not when your IDE/editor tells you :P
you should not name your client subclass run. Instead name it something else. usually the name of your bot is used instead
when you do that, it makes it just really confusing for people actually reading the code and yourself
for example, this is mine
class KumikoCore(commands.Bot):
"""The core of Kumiko - Subclassed this time"""
def __init__(
self,
intents: discord.Intents,
session: ClientSession,
pool: asyncpg.Pool,
redis_pool: ConnectionPool,
lru_size: int = 256,
dev_mode: bool = False,
*args,
**kwargs,
):
...
and line 4 is pretty much not needed since line 5 is already a subclass of discord.Client
so effectively they are the same thing
src/bot.py lines 17 to 24
class Skurczybyk(commands.Bot):
def __init__(self) -> None:
self.logger = Logger(name="Skurczybyk")
self.http_session = aiohttp.ClientSession()
self.config = Environment()
self.prisma = Prisma()
super().__init__(command_prefix=".", intents=nextcord.Intents.all())```
prisma?
yes, prisma
i used the prisma python client before and it takes like 250MB of ram
so thats like nothing
i just use asyncpg instead. my bot's memory went from like 250MB to 75MB
it is quite a bit for me
my goal is to cut down memory usage as much as i can, so asyncpg made more sense
makes sense
plus using sql pretty much gave me all of the control when it came to writing queries. with prisma, it was so wacky and you end up being constrained with what the library offers
didnt have to write so complex queries yet
I hear bad things about Prisma Python client
im just so amazed with the type safety and real time typehints so thought ill use it for a project
Which is a shame because I really liked their TS client and I hear very good things about their Rust client
But I am also starting to move away from ORMs these days so 
SELECT pin.content
FROM pin_lookup
INNER JOIN pin ON pin.id = pin_lookup.pin_id
WHERE pin_lookup.guild_id=$1 AND LOWER(pin_lookup.name)=$2 OR LOWER($2) = ANY(aliases);
this is like an example of one of mine
also some of my queries depend on pg_trgm, which i dont think prisma supports
prisma originates from javascript doesnt it
yea
i mean i tried all sorts of orms. sqlalchemy, tortoise orm, prisma, piccolo, django orm, etc
didn't like any of them
i cant share my opinion yet thats my first orm in python and all i tested it with were basic queries and i liked it 
ORMs are fine for basic stuff but it ends up becoming a footgun later on from my experience
that
One of the groups I'm part of uses an ORM and as our project got more complex we spent more and more time fighting SQLAlchemy
yea. for me, i wasted a ton of time fighting the orms and spent a lot of time just reading the docs
but in the end you know some sketchy methods to do stuff in it
True, but you really shouldn't have to do that
yeah but i guess if its really so hard to do some query you can hard code it, misses a point of the orm but yeah
by hard code i mean write actual SQL query in string
ORMs also sometimes produce really arcane SQL that is hard to debug
Regardless, off topic for this channel ๐
originated from discord bot ๐ 
What is event decorator?
I tried that and use command and getting this error
AttributeError: 'Client' object has no attribute 'command'
I use sparkedhost
dont use sparkedhost
you need Bot instance to use commands framework, not Client
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin) to provide the functionality to manage commands.
Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree) and is automatically set upon instantiating the class.
async with x Asynchronously initialises the bot and automatically cleans up.
New in version 2.0.
Why?
Please make sure you read this fully
When you look for hosting your bot, you might be tempted to use free services or providers that claim to support hosting discord bots (eg PebbleHost and others). Do not uses them. Why? Let me explain.
Free hosts and tiers always have drawbacks - The point of a free tier or a host is to get the user to use their product, and upgrade for all of the good features. Hosts such as replit (see ?tag replit for more info) use shared cpus, oftentimes will run into ratelimits, and have "gotchas" that make you tempted to upgrade to their paid tiers. They also literally remove all control out of how you run your bot. Think about it: Hosts need to make money somehow in order to either break even or gain profit. So naturally they will tempt you into upgrading in order to do that. This is basic economics and quite literally how businesses run.
If you are still looking for a host after reading this, then you have some options. And here are them:
-
Pay up - Pay up and use a VPS provider. My pick is Heznter, but see
?tag vpsfor the full list (if you are on the Python discord server, then see!hostingfor your options). More than likely if you are not an eligible HS or uni student, this is your option. -
Self Host - If you are able to self host your own server, then go for it. This is really the only "free" way if you already pay for your electricity bill and have the equipment to do so
-
GitHub Student Developer Pack - IF you are an eligible student in an verified HS or college (you will need to either provide an valid student ID or proof of education of your HS or college. school transcripts work in this case), then you may apply for this deal. The deal offers $200 free credits on DigitalOcean for 6 months, so if you are a student and need to host your bot, go for it.
Need to run your bot 24/7? Get a cheap VPS.
https://www.scaleway.com/ EU https://www.time4vps.eu/ Lithuania.
https://www.digitalocean.com/ US https://www.vultr.com/ US
https://www.ovh.co.uk/ EU/Canada https://www.hetzner.com/ Germany/US
Self-hosting: Free hosting: Kinda free:
Any computer. Heroku dead ๐ฆ GCP, AWS have one year free micros.
Affordable and powerful VPS Hosting in Europe. Linux, Windows and Storage VPS available from 1.99 EUR/month.
!hosting
Using free hosting options like repl.it or Heroku for continuous 24/7 bot hosting is strongly discouraged.
Instead, opt for a virtual private server (VPS) or use your own spare hardware if you'd rather not pay for hosting.
See our Discord Bot Hosting Guide on our website that compares many hosting providers, both free and paid.
You may also use #965291480992321536 to discuss different discord bot hosting options.
Thanks guys. My codes works fine when i tried locally on my computer in visual studios
ok
yo please how can i use interaction.response.edit_message method for a specific embed ?
this is for interaction only
if you want to edit message in other channel use message.edit()
oh so i would just ake something like embed.edit or something likle that depending on the pycord method
Why use pycord though
didn't notice sorry ๐น
if embed will be Message object sure
i learned it before realising that there is other forks ๐น
!d discord.Message.embeds
A list of embeds the message has. 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.
yes thanks
.edit(embed=updated_embed)
yes that's what i thought first
- what library is that
- where is this code placed. Is it inside any class
Pycord I think
I think your discord is just cooked lol
Now code formatting on mobile is a whole different conversation
what build is that
bro idek I just click update when it needs to be updated ๐ญ
Stable
If that's what you mean
192
issues with being beta tester i guess
iirc android has code formatting
Radical
Discord lacking for iOS mobile smh
fr
pycord
The library has helpers to help create component-based UIs. Shortcut decorators: Objects: Attributes children, disable_on_timeout, message, timeout. Methods cls View.from_message, def add_item, def...
it only takes interaction
but i saw in the docs that i can write button too
where?
Learn all about implementing buttons in your Discord Bot using Pycord.
but i don't use class method so idk if that's important
cb.disable ??
try
a
send the code and error
import discord
import os
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)
# Initialize the Discord client
intents = discord.Intents.default()
client = discord.Client(intents=intents)
# Replace 'YOUR_BOT_TOKEN' with your actual bot token
BOT_TOKEN = 'YOUR_BOT_TOKEN'
@client.event
async def on_ready():
print(f'Logged in as {client.user.name}')
@client.event
async def on_message(message):
# Check if the message was sent by the bot itself
if message.author == client.user:
return
# Check if the message content is "online" (case-insensitive)
if message.content.lower() == "online":
await message.channel.send('1')
else:
await message.channel.send('2')
# Start the bot
client.run(BOT_TOKEN)
I want the bot to return 1 when I send "online" in the server, otherwise I want it to return 2. This is for testing purposes
And what's happening when you try it out
You have both a client and a bot
(side note, don't use client and bot, pick one based on your needs and stick to it)
Ok so I should only import discord? I'll try that
What
I get that there's a proper way to do things...
Nobody said that
Oh you meant the intents thing, I don't know anything about that
discord.ext.commands.Bot is a subclass of discord.Client, so the choice is obvious
I'm really new at this
discord.py might seem like a beginner library, but it's not
Learning at least OOP and async programming is basically a requirement
If you learn by making projects, make smaller projects first
I'm making a botnet
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
any way to hide a slash command for everyone except for specified User IDs
They send an online notice to the discord server and I need the bot to pick that up
I just don't understand how this is not a simple problem
It's a very simple problem, that's the problem
oh so I'm being gatekept
If you can't solve this problem I don't understand how you'll be able to create a whole bot
I already tried google and chatgpt so this is where I'm at
No? This isn't some super secret solution
Most people in this server aren't just going to spoonfeed you
Well why can't you share the problem. I'm working in vb.net and batch
I'm not paying for school just to be treated like this
no, we just aren't supposed to help with malicious intent projects
Okay, you have instances of both discord.Client and discord.ext.commands.Bot which can potentially cause issues. discord.ext.commands.Bot is a subclass of discord.Client so, you'd want to delete your Client instance and use your Bot instance
You had no idea what it was for until I said so
You'd also need message_content intents
I am 100% sure you haven't even tried to reproduce it
You don't need to reproduce the error, it's extremely clear
I don't believe in your methodology and think I it's flawed
I shared you the problem
^
I ment solution
I also shared the solution
Why not just update my code and paste it back to me correctly
dont expect everyone to spoonfeed you
Well, like I said, most people aren't going to spoonfeed you
!rule 9
I have full doubt that you even know what the solution is
its right here
This as well
This means nothing to me
thats literally the soultion?
edit the code yourself
That's some, "Module could potentially cause an issue"
Yes, the 2 instances could potentially cause issues down the line, but I don't believe it's the issue right now (still should fix it)
I believe this is the issue at hand
@obsidian fable I doubt you even know what this is about but you're taking a side.
I'm seriously not here to argue
Your instance of discord.Message.content is probably None, therefore it's going to always respond with 2
!d discord.Intents.message_content
Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:
โข The message was sent by the client
โข The message was sent in direct messages
โข The message mentions the client
This applies to the following events...
This is the solution
I've seen him around in this channel, I believe he's sufficient with the knowledge to solve your problem
You've been told the issue your facing, and been provided the solution
Do whatever you want with the information
As a side, I always spoon feed people the information
I guess we follow different guidelines then
I just call it being helpful... I'll see what I can do with the information you provided
I believe that spoonfeeding doesn't help a person learn as they will just take the code, implement it into their program and move on in 95% of cases
Telling somebody the issue, then providing the resources to create a solution forces a person to somewhat understand the code they're writing
Ok so deleting the client completely breaks it
Yes, you need to remove discord.Client and exclusively use discord.ext.commands.Bot
you have two discord clients going on
bot = commands.Bot(command_prefix="!", intents=intents)
intents = discord.Intents.default()
client = discord.Client(intents=intents)
remove one of them
^
did you toggle intents in the discord developer portal
no
do that first
Well yes, I mentioned the intents were the issue
so it needs intents, understood
^
hey, is there a way i can make it so i can make a discord bot take messages from a specific channel in another server and send those messages in my own server?
Yes, not sure if this is okay with TOS though
Data privacy and allat
Anyway
Hello
even though the bot isnt in the server that the messages should be retrieved from?
Um, no?
It has to be the server to see the messages
Okay what you're doing probably breaks TOS
Trying to copy messages of servers that you're not in
oh alr
Not gonna help with that
Hello
why do you need this
Pretty obvious imo
so i can get info about commissions from different places into my own server
Privacy violations
@final iron I fixed my problem
Good for you
import discord
import os
intents = discord.Intents.default()
intents.typing = False
intents.presences = False
intents.message_content = True # Enable message content intent
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
print(f"Received message: {message.content}")
if message.content.startswith('hello'):
print("Detected $hello command")
await message.channel.send('Hello!')
# Use 'TOKEN' without percent signs
client.run(os.getenv('TOKEN'))
Me when people post the most random code
Im posting it incase someone else has the same problem
What is the code supposed to do lol

It replies Hello! when you send hello to the server the bot is it
U know there is something called ext.commands
People won't try to find someone with the same issue. People are lazy and will ask
what's that?
If they don't get an answer they'll scream and not search on their own, and definitely not search in this channel 
I used chatgpt to solve the problem
If you need commands, use the commands extension.
Docs: https://discordpy.readthedocs.io/en/latest/ext/commands/commands.html
Why should I use the commands extension?
- Prevents spaghetti code
- Better performance
- Easy handling and processing of command arguments
- Argument type converters
- Easy sub commands
- Command cooldowns
- Built-in help function
- Easy prefix management
- Command checks, for controlling when they're to be invoked
- Ability to add command modules via extensions/cogs
- Still able to do everything you can do with
Client
There we go ๐คก
Bruh really
Yeah it's so much more heplful then people
ChatGPT is jackshit anyways
Works for me, very well
Data is outdated and it's just getting dumber and dumber
Love the
I fixed my problem
when you did absolutely nothing and just pasted what the AI told you
I use persistance so it's very helpful for me
Nah dude, I actually asked it the right questions
Gonna have to guide your persistence to another path. Good motivation but working in the wrong path
And then people will come back because they got some old code from that AI
Y'all sheep
Lol
Says the ๐ doing like everyone and asking AI then copy paste code 
How long have u been using dpy?
I've been using dpy for 2 years. Started all the way back when v1 was a thing
I couldn't care less
v0.x gang
nice i know someone who is in the v0.16 gang
The intents thing is weird but other than that it seems pretty straight forward
blame discord for intents
ddevs wanted to kill off prefixed commands essentially
It's just for enabling extra functions right?
yes. and some of those extra permissions are required
eg message_content
Exactly yeah
I wish someone could have just explained that earlier like I said it was pretty straightforward I just needed to ask chatgpt
Google wasn't helpful either
u know chatgpt's data is outdated for dpy right
gpt3.5? yeah the cutoff is 2021
so chatgpt literally knows nothing about dpy v2
I had gpt4 but gpt3 worked fine you just need to convince it to check its database
I realize that
so if you are looking for v2 help, then good luck with chatgpt
It worked fine
"worked fine"
You just need to convince it to break the box
nah it's called building your own programming skills
i hate it when people depend on chatgpt like it's life support
That's fair
Welcome in 2023
yep 2023 moment
I mean it's like depending on the internet but whatever
It's the same as depending on google
You probably wouldn't be much of a programmer if you couldn't read a help file online
Using AI everywhere for everything. People won't bother to learn and then call themselves "Developers" or "Legendary Developer" or whatever, although all they do is ask AI
anyways, you just got done with quite literally the most basics of dpy
small victory for me
you've got a ton of ground to cover if you want a deeper dive
Next I'm going to have the bot download .txt files that I send to it to populate a database
would suggest looking at the source code for R. Danny if you want to see the inner working of a dpy bot
ah shit not again
files are not databases
nosql?
SQL is pretty much the de-facto standard for bots
why? most data that you will store for your bot are relational. here's an example: Say that i'm building an economy module for my bot. I need to store how much coins a user has, the inventory of the user, and other data. Now one user can have multiple items and jobs, and another user can have the same jobs but different items. you essentially need to build relationships between these, and that's what SQL does best
It's not going to be very complex, just the name of a machine , it's ipv4 and ipv6 address if it has one. I'll use that data later
alright. I've used sql for crypto mining servers before but that's it
it was all software i hadn't written so i've barely touched it
ok
You figured out how to set an attribute to true. Good job
Thanks lol
hi. whats the problem? yesterday its fix but now not :|
do you have multiple python versions installed in your pc?
also calling your file Discord.py is not the best choice
How do i ensure that after my bot reboots, the drop down menu and buttons remain valid
i know a bit of this that it has to do something with these 2 parts of my code:
https://srcb.in/KWSNQ4ZO1S
and
https://srcb.in/6QJ3zIrl5O
its meant change my file name?
@glad cradle
first, allow your file i.e trust is... second... when u hover over the name of discord and discord.ext what comes up?
try reboting your pc, that usually fix the issue for me
ok
@terse knoll
Namespace and venv issues
The Python interpreter can't find your Python file
Your file has a backtick and the command that is running it removes it
Just remove the backtick and run it again
@quick brook i have q
how can i give roll too all members?
does anyone know why, when i start a tasks.looop in another loop, then close that loop, why doesnโt it start the other loop. ive tested everything and it just doesnโt start
I believe the only way is just iterating over all members and giving each a role
!paste
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
@bot.event
async def on_message(message):
tax_channel = bot.get_channel(1145303393963872357)
if message.channel == tax_channel:
if "k" in message.content:
message.content.strip("k")
number = message.content + "000"
await tax_channel.send(number)
Why the bot start spamming when I send 50k?
https://paste.pythondiscord.com/HITQ my cog is not doing anything on the listeners
Cause you named them the same on_message
!e ```py
def func():
print(1)
def func():
print(2)
func()
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
2
Only the last one will actually work
If you wanna have many in one cog
Do this instead
no there on_message_edit and on_message
oh wait
nvm
@listener("on_message")
async def some_cool_name(...):
...```
ok thanks
listener is not defined
oh ok
Obviously replace it with commands.Cog.listener
ik
How I can check if is there number in message?
!d str.isdigit
str.isdigit()```
Return `True` if all characters in the string are digits and there is at least one character, `False` otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers. Formally, a digit is a character that has the property value Numeric\_Type=Digit or Numeric\_Type=Decimal.
!e ```py
print("1.23".isdigit())
print("123".isdigit())
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | False
002 | True
a number that ends with bd ?
50 works + 50hd but bd only not
K or m
can you show examples
I want if the message doesn't have number the bot delete it
Example:
If I send hs the bot will delete it
But if I send 50hs the bot will make another thing
- does it only work with 50 or any number
- what are the string suffixes that work
Nope, with any number
k & m
so
123ks -> works
123ms -> works
hs -> fail
12hs -> works
``` ?
Only
Digit only & digit with M & digit with k
r'(?P<number>\d+)(?P<suffix>[kmh]s)' this regex might work
but im not sure if i understood correctly
I don't understand this
!e ```py
import re
pattern = r'(?P<number>\d+)(?P<suffix>[kmh]s)'
test_strings = ["123ks", "123ms", "hs", "12hs"]
for string in test_strings:
match = re.match(pattern, string)
if match:
print(f"String: {string} - Number: {match.group('number')}, Suffix: {match.group('suffix')}")
else:
print(f"String: {string} - No match")
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | String: 123ks - Number: 123, Suffix: ks
002 | String: 123ms - Number: 123, Suffix: ms
003 | String: hs - No match
004 | String: 12hs - Number: 12, Suffix: hs
Just stripped the k and make the bot check if the stripped is digit
But this happend
Looks like you are trying to reply to deleted message
Ah
check if author is bot itself
!e sure :)
def command(guild_id):
if (var := getattr(__builtins__, f"guild_var_{guild_id}", None)) is not None:
print(var, "ye")
else:
setattr(__builtins__, f"guild_var_{guild_id}", {"data": f"{guild_id} thing"})
print("No")
command(10)
command(10)
command(20)
command(20)
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | No
002 | {'data': '10 thing'} ye
003 | No
004 | {'data': '20 thing'} ye
a stupid question:
can i store my data in a discord channel instead of a database?
why would you want to do that
- i dont wannna use a database
- same as reason 1
if you wanna make your life harder sure you can try
but i dont see a reason to not wanna use a tool that is literally created to store data
i understand not everyone likes SQL and vice versa but there are plenty of databases on the market
well... not life harder... tbh i prefer sqlite, i'm mainly asking cause i wanna test some stuff... basicaly play and mess with stuff
what are you trying to test that would require you to do such a thing
you are shooting yourself in the foot
mainly cause i am bored, and i just wanna see how stuff can be done
does anyone know why, when i start a tasks.loop in another loop, then close that loop, why doesnโt it start the other loop. ive tested everything and it just doesnโt start
would be easier to understand if you shown code
Send anything you want to the channel and get the messages later. But as already said, very weird and ineficcient way to store the data
before i do, is tracking my crypto currency wallet against tos? because i am checking how many confirmations a bitcoin transaction has that has been sent to me
no idea im not that into crypto
alright
so this tracks incoin transaction and then the confirm_checker loop doesnt seem to start, and i have no idea why```py
@tasks.loop(seconds=10)
async def incoming_trans(channel_id, message_id):
print(message_id)
channel = bot.get_channel(channel_id)
con,cur = openCON()
cur.execute(f"SELECT * FROM db WHERE channel_ID = '{channel_id}'")
i = cur.fetchall()[0]
key = PrivateKey(i['crypto_wif'])
address = i["address"]
transactions = key.get_transactions()
req_btc = shorten_btc(req_amount-0.00001656)
btc_bal = float(key.get_balance(currency='btc'))
btc_price = float(requests.get('https://blockchain.info/ticker').json()['USD']['last'])
usd_am = key.get_balance(currency='usd')
if btc_bal >= req_btc:
# msg = await channel.fetch_message(message_id)
# await msg.delete()
embed = discord.Embed(title="New Transaction", description=f"The amount of {req_amount} ({usd_am} USD) has been detected", color=discord.Color.light_grey())
embed.set_thumbnail(url="https://cdn.discordapp.com/emojis/1145663841955500042.gif?size=240&quality=lossless")
confirm_checker.start(channel.id)
print(9)
incoming_trans.stop()
print("started")
@tasks.loop(seconds=10)
async def confirm_checker(channel_id):
channel = bot.get_channel(channel_id)
on,cur = openCON()
cur.execute(f"SELECT * FROM db WHERE channel_ID = '{channel_id}'")
i = cur.fetchall()[0]
key = PrivateKey(i['crypto_wif'])
trans = key.get_transactions()
data = requests.get(f"https://blockstream.info/api/tx/{trans}").json()
print(f"https://blockstream.info/api/tx/{trans}")
status = data["status"]
confirmations = data["status"]["confirmed"]
print(1)
if confirmations == "true":
await channel.send("complete")
print(2)
print(status)
print("done")
confirm_checker.stop()
else:
print("nothing")```
first of all dont use requests library in discord bot, its blocking
huh
!blocking
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!
oh ok
and u think this might be why the second loop isnt starting?
no idea just first thing i noticed
oh
so what do u think is the problem?
How did you start it?
Do you get some errors? What output do you get from prints? Because simplified version works fine
@tasks.loop(seconds=3)
async def task1():
global i
i += 1
print(i)
if i == 3:
task2.start()
print("started")
task1.stop()
print("stopped")
@tasks.loop(seconds=3)
async def task2():
print("+++")
1
2
3
started
stopped
+++
+++
global ๐ฟ
Testing 
i started it when a button was clicked
no errors and i only get the outputs from the first tasks.loop
Try to add a print right in the start of the function.. Maybe you got something that is taking a lot of time in that task
okay
hey please how can i delete an interaction message like msg = await interaction.respond.send_message(. . .)
the api that i am getting the transaction info from says "status":{"confirmed":false}}, so when checking if confirmed is true, do i do True or "true"?
await interaction.delete_original_response
If u read the docs then you would have found it pretty easily
thanks
Next time please read the docs
If it's false and not "false" then yeah, do True
okay
Rtd
rohh
or canโt u do await interaction.message.delete()?
interaction.message only exists if it was runned from message
so this wouldnโt work
why i can not download discord-component library in pycharn . its saying failed
is there another way to add buttons
Unfortunate, maybe just use discord.py
Don't use that in first place
then how can i add buttons
It's non-compatible as far as i know
This repository has been archived by the owner on Dec 18, 2021. It is now read-only.
It's discontinued.
Nice code, but we don't need it
I get this error when I try to send a message to a specific channel. Any ideas?
await bm_channel.send("**BM IS ON**")
^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'send'
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.
i just showing the problem
No point, we're telling you to use discord.py instead
i already use it but its not working
its still have the error
No you're clearly not
It seems that you are unable to get the channel
can i add buttons with discord.py library?\
You can get from cache only after running the bot. When you just defined bot variable, it hasn't data.
Do that after running or use something like discord.PartialMessageable
Move that bm channel variable to after your on_ready event inside the on_message event
Again, for the third time ^^^^^^^^^^^^^
Look. at. the. examples.
Thx. Works perfect
The reason for the error was that you were trying to get channel before your client was ready
Ok, cool. God to know. I have another question. The command only works when I write bm and not !bm
ok i figure out what is stopping it
Yeah because it's not a command
It is an event
should it be on_command?
For commands (especially prefix commands) you need to use commands.Bot instead of discord.Client
Ok, thx. I will check that link out
This is an example
@buoyant quail i printed trans and it gave me ['blah blah'], woll that effect anything when i put it into data = โฆ.
You are trying to use it as dictionary and it's a list here so uhm yes
i tried this way and i have an error
Traceback (most recent call last): File "C:\Users\pirat\PycharmProjects\pythonProject\main.py", line 1, in <module> import discord File "D:\pythonProject\lib\site-packages\discord\__init__.py", line 25, in <module> from .client import Client File "D:\pythonProject\lib\site-packages\discord\client.py", line 53, in <module> from .webhook import Webhook File "D:\pythonProject\lib\site-packages\discord\webhook\__init__.py", line 11, in <module> from .async_ import * File "D:\pythonProject\lib\site-packages\discord\webhook\async_.py", line 41, in <module> from ..channel import PartialMessageable ImportError: cannot import name 'PartialMessageable' from 'discord.channel' (D:\pythonProject\lib\site-packages\discord\channel.py)
import discord
import random
import asyncio
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
client = commands.Bot(command_prefix='!', intents=intents)
suits = {
'hearts': 'โฅ๏ธ',
'clubs': 'โฃ๏ธ',
'diamonds': 'โฆ๏ธ',
'spades': 'โ ๏ธ'
}
numbers = list(range(2, 11))
high_value_cards = ['K', 'Q', 'J', 'A']
cards = [(number, suit) for suit in suits.keys() for number in numbers] + [(card, suit) for suit in suits.keys() for
card in high_value_cards]
@client.event
async def on_ready():
print('Bot is ready')
@client.command()
async def bj(ctx):
channel = client.get_channel(1145730366963990619)
if ctx.channel.id != channel.id:
return
if not cards:
embedVar = discord.Embed(title="Dealer is Shuffling the deck!", color=ctx.author.top_role.color)
shuffle_message = await ctx.channel.send(embed=embedVar)
await asyncio.sleep(3)
await shuffle_message.delete()
cards.extend(
[(number, suit) for suit in suits.keys() for number in numbers] + [(card, suit) for suit in suits.keys() for
card in high_value_cards])
random.shuffle(cards)
random.shuffle(cards)
player_hand = []
total_sum = 0
ace_count = 0
# Deal the first two cards
for _ in range(2):
card = cards.pop()
if card[0] in high_value_cards:
if card[0] == 'A':
if total_sum + 11 <= 21:
random_num = 11
ace_count += 1
else:
random_num = 1
else:
random_num = 10
else:
random_num = card[0]
player_hand.append(f"{card[0]} {suits[card[1]]}")
total_sum += random_num
while total_sum > 21 and ace_count > 0:
total_sum -= 10
ace_count -= 1
if total_sum == 21:
result = "Your hand: \n" + ", ".join(player_hand) + "\nTotal: " + str(total_sum) + "\nBlackjack!"
else:
result = "Your hand: \n" + ", ".join(player_hand) + "\nTotal: " + str(total_sum)
hit_button = discord.ui.Button(style=discord.ButtonStyle.green, label="Hit")
stop_button = discord.ui.Button(style=discord.ButtonStyle.red, label="Stop")
view = discord.ui.View()
view.add_item(hit_button)
view.add_item(stop_button)
embedVar = discord.Embed(description=result, color=ctx.author.top_role.color)
await ctx.channel.send(embed=embedVar, view=view)
@client.event
async def on_button_click(interaction):
if interaction.custom_id == 'hit':
# Add your hit logic here
pass
elif interaction.custom_id == 'stop':
# Add your stop logic here
pass
where is the error
`# Add your stop logic here` 
The if else nesting ๐
You can use if with and for conditions like this
Or at least guard clauses
why everyone do client = commands.Bot ๐ญ
its working thanks you so much
๐
I do async with commands.Bot as bot
U also know that dpy natively supports all of the UI components right
That's why we told them to use discord.py and durch that outdated and archived package
Theyโre probably watching some shitty youtube tutorial.
crap
I dont get it. I tried this with a error.
ERROR discord.ext.commands.bot Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "test" is not found
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.
@bot.command()
U forgot the ()
Thanks guys!
mh what library are you using
py.discord
examples/advanced_startup.py line 91
async with CustomBot(commands.when_mentioned, db_pool=pool, web_client=our_client, initial_extensions=exts) as bot:```
do you have any idea what about this
mh didn't knew that Discord.py implements __aenter__ and __aexit__
https://github.com/Rapptz/discord.py/blob/master/discord/client.py#L297-L308
discord/client.py lines 297 to 308
async def __aenter__(self) -> Self:
await self._async_setup_hook()
return self
async def __aexit__(
self,
exc_type: Optional[Type[BaseException]],
exc_value: Optional[BaseException],
traceback: Optional[TracebackType],
) -> None:
if not self.is_closed():
await self.close()```
probably you're not responding to the interaction
or there's an error in your code
but you should see it in this case
Dpy v2
wdym
hit_button = discord.ui.Button(style=discord.ButtonStyle.green, label="Hit")
stop_button = discord.ui.Button(style=discord.ButtonStyle.red, label="Stop")
view = discord.ui.View()
view.add_item(hit_button)
view.add_item(stop_button)
embedVar = discord.Embed(description=result, color=ctx.author.top_role.color)
message = await ctx.channel.send(embed=embedVar, view=view)
try:
interaction = await client.wait_for("button_click", check=lambda i: i.component.label in ["Hit", "Stop"], timeout=60)
if interaction.component.label == "Hit":
card = cards.pop()
if card[0] in high_value_cards:
if card[0] == 'A':
if total_sum + 11 <= 21:
random_num = 11
ace_count += 1
else:
random_num = 1
else:
random_num = 10
else:
random_num = card[0]
player_hand.append(f"{card[0]} {suits[card[1]]}")
total_sum += random_num
while total_sum > 21 and ace_count > 0:
total_sum -= 10
ace_count -= 1
result = "Your hand: \n" + ", ".join(player_hand) + "\nTotal: " + str(total_sum)
embedVar.description = result
await message.edit(embed=embedVar)
elif interaction.component.label == "Stop":
await message.edit(content="Game stopped.", view=None)
except asyncio.TimeoutError:
await message.edit(content="Timeout: The game has ended.", view=None)
Is button_click even an event?
What library is this?
Itโs not an event in dpy, even if it was, I really donโt think you should be overwriting the callback with it
can you help me with it?I'm confused
^
Use callback
can you help more pls?im really comfused
Is it possible to the send a message if user writes only !bm? !bm load works
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.
Just remove the arg or give it a default value
A default value?
Yes. As you would do in a normal function
I dont get it. Maybe I have to study it more
Let's say you have such function
def f(x):
return x
assert f(3) == 3
assert f() == 5
how would you achieve that by changing only the function definition? (to not get errors)
!paste
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
https://paste.pythondiscord.com/H6EA
Traceback (most recent call last):
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/ext/commands/bot.py", line 935, in _load_from_module_spec
spec.loader.exec_module(lib) # type: ignore
File "<frozen importlib._bootstrap_external>", line 850, in exec_module
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "/Users/zagzag/vscode/zagzag/cog-folder/moderation-commands.py", line 10, in <module>
class ModerationCog(commands.Cog):
File "/Users/zagzag/vscode/zagzag/cog-folder/moderation-commands.py", line 25, in ModerationCog
@app_commands.commands(name="kick", description="kicks a user (moderator only)")
TypeError: 'module' object is not callable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/zagzag/vscode/zagzag/zagzag.py", line 786, in <module>
asyncio.run(main())
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 642, in run_until_complete
return future.result()
File "/Users/zagzag/vscode/zagzag/zagzag.py", line 782, in main
await bot.load_extension(f'cog-folder.{filename[:-3]}')
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/ext/commands/bot.py", line 1013, in load_extension
await self._load_from_module_spec(spec, name)
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/ext/commands/bot.py", line 938, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cog-folder.moderation-commands' raised an error: TypeError: 'module' object is not callable``` im having this error
You want @app_commands.command i guess
Was worth a try but it was not the way ๐
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.
oh boy json as db
as what is the "load" arg supposed to do?
are you interested in creating options or subcommands
Subcommands. !bm should be one command. !bm load is another one
then you have done it incorrectly
Yes, I know. I try to figure it out
@commands.group(invoke_without_command=True)
async def your_command_name(self, ctx):
do_your_functions()
@your_command_name.command()
async def sub_command_name(self, ctx):
do_your_subcommand()```
See: <https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.group> for documentation
This was the last test
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.
Ok, I'll check it out. Thanks



