#discord-bots
1 messages · Page 934 of 1
why did you put brackets i think you should try without them
if (.. -> if not
it working with this
but let me try
!d discord.ext.commands.has_guild_permissions
@discord.ext.commands.has_guild_permissions(**perms)```
Similar to [`has_permissions()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.has_permissions "discord.ext.commands.has_permissions"), but operates on guild wide permissions instead of the current channel permissions.
If this check is called in a DM context, it will raise an exception, [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage").
New in version 1.3.
still doesn't work but here's the code
Yeah manage_server doesn't exist
try manage_messages
so what should I put
its againts links so manage messages ig?
Does anyone know if its possible if you can make a python script that scans for a certain word on the screen? like with ocr or something like that?
administrator yeah ty
im so sorry im blind 😂 this was the first channel that popped up when i clicked the server my apologies
class View(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
for i in range(3):
for j in range(3):
self.add_item(item=(discord.ui.Button(label="\u200b", row=i, custom_id=("button" + str(i) + "," + str(j)))
@button(label= "\u200b", custom_id="button0,0", row=0)
async (error: for expected) def counter(self, button: discord.Button, interaction: discord.Interaction):
button.emoji = "❌"
await interaction.edit_original_message(view=self)
Why does Python tell me there s a "for" expected in async def counter?
?
for expected
nah what i mean is that is where its telling me that "for" is expected
interaction.edit_original_message is used to edit the messages sent with interaction.response.send_message
it doesn't work because you didn't send a response message with that interaction beforehand
dont be rude please
poorly described mb
you tell me
no worries
im not doing anything, i was just making sure you were helping in a polite fashion
sorry found the error forgot a ) at the for loop
but one more question
is my thought right that if i self.add_item in the class it makes multiple items in the View right?
so technically how would i be able to edit an item?
lets say i have 5 items which are buttons, how would i access that item and edit it?
So I want two things. The first is I want to add a premium system in which when someone boosts the support server will get a role which will give him/her premium for the bot. Secondly I want to add the ability for the users to setup things for the bot in their servers. The problem is that I don't know how to create both of these things I told
If someone can help me it'll be very good
why does fetch_users give me <coroutine object Client.fetch_user at 0x00000261D72D8430>
show code
print(userid)
useracc = client.fetch_user(int(userid))
print(useracc)```
you have to await it
ok one sec
thanks
worked
can you explain why that happens though? what does await mean
coroutines are async functions in Python'
when you use await, which can only be used in functions marked as async def, it suspends the execution of the function and passes it on to the event loop
ok thanks
every async function returns a coroutine'
bro
me ena kalo search to prwto to vriskeis kai egw to exw kanei alla den to thimame na s to pw
!rule 3
4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.
nai alla ti prepei na kano search 😅
dm'
sorry
Ñ
whats happening here
Typo in mention_amount maybe?
its because you set name to be the same as the command name.
Rename ur command
Slash command names cannot have a capital letter
all my commands have upper on name but command is lower and they work fine except this one
🤔
yea im lost
@slash.slash(name="Delete",description="delete servers on your Safecloud-hosting panel.")
async def delete(ctx,serverID):
pass
r = api.servers.list_servers()
oc = 0
try:
for i in range(100):
server_name = r[i]['attributes']['name']
SID = r[i]['attributes']['id']
uuid = r[i]['attributes']['uuid']
nc = oc + 1
oc = nc
if serverID == f"{uuid}":
api.servers.delete_server(server_id=SID)
await ctx.send(f"{server_name} has been deleted!")
except IndexError:
await ctx.send()
heres my code
I guess discord must've changed the regex or something, because I remember uppercased names not being allowed
how to make such a thing?
well and how can i make it to update the id of the message?
This traceback barely gives any info, are you sure 100% that it's the delete command causing this error?
if i take it out of my code theres no error
heres a copy of a good command and the bad
why is my bot not saying anything?
The command -a does not exist in the code but it still says nothing please help fast I want to go to sleep
is there anything i need to get started on a music bot
code? errors?
Code is in the screenshot and there are no errors
well on the other error handler it works
not the function
!d discord.discord.ext.commands.on_command_error
discord.ext.commands.on_command_error(ctx, error)```
An error handler that is called when an error is raised inside a command either through user input error, check failure, or an error in your own code.
A default one is provided ([`Bot.on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.on_command_error "discord.ext.commands.Bot.on_command_error")).
what the
yep weird dir right
it's the same for other libs what


it's discord.on_command_error on the doc command
wdym
arent on_command events under /ext/commands/
well yeah
can anyone helpp
how do i get the id of all people i've dmed before
Automating that is against Discord's terms of service
Unless you're talking about all the users your bot has dmed before
You're.. logged in as your bot?
huh
I'm not quite following
Are you trying to get the ID of everyone your bot has DMed or everyone you have DMed?
but you cant log in to a bot
In a way that doesn't break TOS? No
There are ways to, at least there were but obviously against terms
bruh how do i get the id of everyone my bot has dmed
That's easier, bots have a private_channel attribute
that is what i meant all along
keep_alive()
NameError: name 'keep_alive' is not defined``` need help
Keep in mind that includes both dms and group chats so you have to filter it
Replit?
since when could bots be in group chats
yes sirrr
Best option would be to get off replit
python
For a while
ok so how do i do it
!d discord.Client.private_channels
property private_channels```
The private channels that the connected client is participating on.
Note
This returns only up to 128 most recent private channels due to an internal working on how Discord deals with private channels.
how do i get more than 128 most recent
🤔 Bot's cannot be in group chats
Alright then you don't have to filter it ¯_(ツ)_/¯
yeah cuz u would have to add the bot as a friend to add it to a group chat
You can safely assume they'll all be DMChannels then
(I don't know how well that's typehinted so your editor may or may not let you make that assumption)
As it says, it's a Discord limitation so you can't
ok
Quesiton does anyone know how i purge only a certain members messages
await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.
You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own. The [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.
Changed in version 2.0: The `reason` keyword-only parameter was added.
Examples
Deleting bot’s messages...
@compact ruin ^
ty
you can't get a list of all users the bot has ever dmed before
only the last 128 users who have been dmed
Anyone know what is this error?
AttributeError: 'Bot' object has no attribute 'AppInfo'
literally read the error, it says 'AppInfo' is not an attribute of the bot object you tried to access it from
you should provide the sample that triggers that error, and maybe give some context as to what you're trying to do in the first place
I'm trying to make the bot send me the console errors from dm
okay that's a simple task, now what code do you have right now to do that?
how can i set a delay to somthing without stoping the whole bot ?
Oops
use asyncio sleep instead of the time stdlib sleep function
import asyncio
await asyncio.sleep(1) # time.sleep(1)```
yeep thats the module i was looking for thx i couldnt rember
@client.event
async def on_error(event, *args, **kwargs):
em = nextcord.Embed(title="❌ Error", description="`%s`" % traceback.format_exc(), color=nextcord.Color.red())
em.add_field(name="Event", value=event)
em.timestamp = datetime.datetime.utcnow()
await client.AppInfo.owner.send(embed=em)
AppInfo is a class from the nextcord package, not from a commands.Bot object
you need to use the application_info() coroutine to grab a nextcord.AppInfo object with information pertaining to your bot
info = await client.application_info()
await info.owner.send(embed=em)```
that should do, although i'm not entirely sure as i haven't had a need to use that method before
just use client.owner and fetch/get 
could do that but uh, they wanna use AppInfo
so i'll direct them to what is relevant
yeh
Aight, thank you
Which was...?
just to clarify this is where i await it right
mhm
client.add_cog() is also a coro
Actually it's not a coro
Not sure why the error is saying it is
You don't have to await it

Something may be wrong in the cog
i can send cog code?
How big is the file?
Monty hall bot ?
hmm?
import discord
from discord.ext import commands
import random
class Example(commands.Cog):
def __init__(self, client):
self.client=client
@commands.command()
async def ping(self, ctx):
""" Pings the client """
latency = round(self.client.latency * 1000)
msg = await ctx.send("Pong!")
e = discord.Embed(title="My ping")
e.add_field(name=f":stopwatch: Latency", value=f"{latency}ms")
await msg.edit("", embed=e)
def setup(client):
client.add_cog(Example(client))```
nah its the name of my bot, based on Monty Python
ah i see
tbh idk
I'm going to sleep now
kk gn
Even I got a discord bot, made it a few weeks ago but now shifted my focus to other projects
its hosted 24/7 tho so ye
Is it possible to check for mass mentions?
@green bluff show your on_ready functipn
!d discord.Message.mentions gives you a list of all mentions in the message
A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.
Warning
The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.
Ty o7
you can use len to get number of all the mentions
No
D:
After a day and a half of writing and refactoring sub-packages, I finally have this to show for it 
you can mention the other and whoever is pinged in that message
@client.event
async def on_ready():
print(f"{client.user} has loaded.")
client.load_extension("cogs.helpcog")```
is that dpy 2.0+
yes
make setup an async function
like?
a coroutine instead of a normal function
bruh you have a setup function in the cog dont you?
# before
def setup(bot):
bot.add_cog(MyCog(bot))
# after
async def setup(bot):
await bot.add_cog(MyCog(bot))
this is the new method.
oh yea
class Example(commands.Cog):
async def __init__(self, client):
self.client=client
@commands.command()
async def ping(self, ctx):
""" Pings the client """
latency = round(self.client.latency * 1000)
msg = await ctx.send("Pong!")
e = discord.Embed(title="My ping")
e.add_field(name=f":stopwatch: Latency", value=f"{latency}ms")
e.add_field(name=" Heartbeat", value=f"{random.randint(100, 200)}ms")
await msg.edit("", embed=e)
@commands.has_role(886780809976107068)
@commands.command(hidden=True)
async def fight(self, ctx, user: discord.Member):
""" Fights a user """
potatoes = random.randint(1, 1000)
await ctx.send(f"{ctx.author.mention} fought {user.mention} with {potatoes} potatoes!")
async def setup(client):
client.add_cog(Example(client))```
this ?
i tried it but i still got an error
clientdoesn't have Cogs or commands.awaitwithclient.add_cogas I believe its a coroutine now
and __init__ should not be async
oh
import discord
from discord.ext import commands
import random
class Example(commands.Cog):
def __init__(self, client):
self.client=client
@commands.command()
async def ping(self, ctx):
""" Pings the client """
latency = round(self.client.latency * 1000)
msg = await ctx.send("Pong!")
e = discord.Embed(title="My ping")
e.add_field(name=f":stopwatch: Latency", value=f"{latency}ms")
e.add_field(name=" Heartbeat", value=f"{random.randint(100, 200)}ms")
await msg.edit("", embed=e)
@commands.has_role(886780809976107068)
@commands.command(hidden=True)
async def fight(self, ctx, user: discord.Member):
""" Fights a user """
potatoes = random.randint(1, 1000)
await ctx.send(f"{ctx.author.mention} fought {user.mention} with {potatoes} potatoes!")
async def setup(client):
await client.add_cog(Example(client))``` so this?
discord.commands.Bot
but i did from discord.ext import commands
so ye same thing ..
doesnt work btw
you need to await the load_extension too
ooh i await client.load_ext
please name the variable bot if you are instantiating Bot
works ye
it is confusing to people helping you since discord.Client exists and client is used for initializing discord.Client
# bad
client = commands.Bot(...
# good
bot = commands.Bot(...```
Both are bad cause you forgot to close the parenthesis
😔 that was just an example andy
Anyway to add a role for a specific amount of time?
Add role, wait X seconds, remove role
await msg.edit(content="UR GAME WILL START IN 5 seconds")
time.sleep(1)
await msg.edit(content="UR GAME WILL START IN 4 seconds")
time.sleep(1)
await msg.edit(content="UR GAME WILL START IN 3 seconds")
time.sleep(1)
can anyone give me the example of the loop so i can do this
For this, if I wanted to check if the message mentioned more than 5 people would it be
if len(message.mentions) <= 5:
#<...>
```?
no, this is checking if its less than 5
- dont use time.sleep, its blocking
- use .ext.tasks.loop
!d discord.ext.tasks.loop
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
you can mention seconds = 1, and do your stuff
idk how they want to do it, they'll get ratelimited prolly
i'd just use an animated emoji which counts from 5 to 1 😂
oh if that can be found it'd be helpful just edit out the emoji after the five seconds
legends
!d asyncio.sleep
coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.
If *result* is provided, it is returned to the caller when the coroutine completes.
`sleep()` always suspends the current task, allowing other tasks to run.
Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.
Deprecated since version 3.8, removed in version 3.10: The `loop` parameter. This function has been implicitly getting the current running loop since 3.7. See [What’s New in 3.10’s Removed section](https://docs.python.org/3/whatsnew/3.10.html#whatsnew310-removed) for more information.
Example of coroutine displaying the current date every second for 5 seconds:
use this, it's async
import nextcord
from nextcord import Interaction, SlashOption, ChannelType
from nextcord.abc import GuildChannel
from nextcord.ext import commands
import config
client = commands.Bot(command_prefix=config.prefix)
tsid = 957233126818578462
@client.event
async def on_ready():
print("Bot ready")
@client.slash_command(guild_ids=[tsid])
async def youtubeslashcommand(interaction: Interaction):
await interaction.response.send_message("Hi I m a youtuber")
@client.slash_command(name="repeat", description="repeat the message", guild_ids=[tsid])
async def repeat(interaction: Interaction, message:str):
await interaction.response.send_message(f"you send this `{message}`")
client.run(config.toke)
my bot is not showing the slash option :/
btw do you guys know any developer groups for python on discord
Wym
for commands.has_any_role, what do I do to a list to make it valid? It's just *list right?
Actually, if I have the list of strings, i need to make it all to integers and then pass it as a list to commands.has_any_role
ok
Yeah iirc it's just *list
Yes, the * is used to unpack the list
why my vs code cant access discord
yeah so first i needed to convert the list of strings to integers then unpack them, now i have this can you review it please
async def has_log_role():
async def predicate(ctx):
async with bot.db.execute("SELECT role_id FROM permissions WHERE guild_id = ? AND command = ?", (ctx.guild.id, str(ctx.command.name))) as cursor:
data = await cursor.fetchall()
role_ids = map(int, data)
role_predicate = commands.has_any_role(role_ids).predicate
return await role_predicate(ctx)
return commands.check(predicate)
@bot.command()
@commands.check_any(has_log_role(), commands.has_permissions(manage_guild=True))
it isnt used yet, thats why it says that
Sure
pip install discord.py
i downloaded it

try restarting your editor
damn
uh then try uninstalling it and installing it back again
pip uninstall discord.py
pip install discord.py
ya
@hearty dust u have two Python versions installed?
rip
wait...what am i missing
@commands.check_any(has_log_role(), commands.has_permissions(manage_guild=True))
this is invalid syntax
dont know
Prolly an unclosed bracket pair in the top lines
let me check
then check 
python version or discord.py version?
python
Go to control panel and list of programs and see the Python installations
@bot.command()
@commands.check_any(has_log_role(), commands.has_permissions(manage_guild=True))
^
SyntaxError: unexpected EOF while parsing```
just use vscode to check 
re-type the line ig
hah
An env?
let me delete discord.py manually
deleted it
install it back again
Hello guys, Im having some problem with my discord bot codes, its returning key errors about the weatherapi, can anyone help
sure
Heres the code
#import thư viện
from datetime import datetime
import pytz
from datetime import date
from discord.ext import commands
import requests
import os
#chỉnh prefix
prefix="?"
#khởi tạo bot
bot = commands.Bot(command_prefix = prefix)
#khai báo biến ngày tháng năm và dùng múi giờ việt nam
my_time =datetime.now(pytz.timezone('Asia/Ho_Chi_Minh')).time()
my_time = datetime.now(pytz.timezone('Asia/Ho_Chi_Minh')).time()
my_date = date.today()
date_rn = my_date.strftime("%d")
month_rn = my_date.strftime("%m")
year_rn = my_date.strftime("%Y")
#event của bot
@bot.event
async def on_ready():
print('We have logged in as {0.user}'.format(bot))
#command của bot
@bot.command()
async def khoidong(ctx):
await ctx.send("Bot đã sẵn sàng!")
@bot.command()
async def dayrn(ctx):
await ctx.send(date_rn)
@bot.command()
async def timern(ctx):
await ctx.send(my_time)
@bot.command()
async def monthrn(ctx):
await ctx.send(month_rn)
@bot.command()
async def yearrn(ctx):
await ctx.send(year_rn)
@bot.command()
async def xemtt(ctx, arg):
cityName = arg
api_key = os.getenv('weather_api')
api_add = requests.get("https://api.weatherapi.com/v1/current.json?key="+api_key+"&q="+cityName+"&aqi=no&lang=vi").json()
temp_city = api_add[0]['current']['temp_c']
weather_desc = api_add['current']['condition']['text']
hmdt = api_add['current']['humidity']
wind_spd = round(api_add['current']['wind_kph']/3.6)
city_name = api_add['location']['name']
time = api_add['current']['last_updated']
report = "Tình hình thời tiết tại {0} được cập nhật lần cuối vào lúc {1}: {2}\n Nhiệt độ: {3} độ C\n Tốc độ gió: {4}m/s\n Độ ẩm: {5}%".format(city_name, time, weather_desc, temp_city, wind_spd, hmdt)
await ctx.send(report)
#chạy bot
bot.run(os.getenv('secret_token'))```
Heres the code
let me down slowly
uhhh
okay so
@bot.command()
@commands.check_any(has_log_role(), commands.has_permissions(manage_guild = True))
this raises invalid syntax, but this doesn't
@bot.command()
@commands.check_any(has_log_role(), commands.has_permissions(manage_guild = True))
async def test():
pass
use hastebin or pastebin to paste your code, and irrc there is a main key in the data, you should check their response and use the suitable keys
but why
I see
Ah
Cz a decorator always needs either a class or a function
you use a decorator above a function or class
The decos are made only for those
When I copy the "xemtt" function codes, paste and run it in another file it runs perfectly
But in the bot file it throws errors
If I change the assign the var cityName to a name of a city in string, it still runs
dms
also which editor
@bot.command()
@has_permissions(administrator = True)
async def kick(ctx, member : discord.Member,*,reason = None):
await member.kick(reason=reason)
await ctx.send(f'{member} has been kicked')
@kick.error
async def kick_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send('No permissions btw')
i did something wrong?
it never works
Which?
the kick command
no errors nothing
@supple thorn bruh we literally got same about me that's a W 🤝
Mines more cursed
yep i can't find the wheelchair in my emojis 😢
How did you use the command?
Kick what
bot = commands.Bot(command_prefix='!', intents = intent)
Yeah but
!kick @slate swan reason
Okay thought you weren't tagging them
nah ,i am tagging
Who are you testing the command on?
Yourself?
no it's my alt
Do you have a on_command_error eating up the error?
i didn't used that
let me use this?
Yeah but do you have one
Does the command work?
probably.... it didn't worked yet tho 
Try and add a print statement in the kick command
Because your code looks right
Also what
aight i'll do it rn
What do you mean probably
it works for my friend
Oh so you copied the code and just pasted it in
So the kick command doesn't work
yea...
Bruh i'm confused what are you having problems with
idk man there are no errors at all.... and everything else with my bot working fine only kick command is not working
Did you restart the bot after you made changes
yes
bro ignore the name tell me about the solution
I don't have to
sed
What's the full error?
ye how to get it
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot 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
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
okk
which module do i need to import for button?
How to make a disboard bump reminder?
@supple thornthank you bro virtual hug to you
have you googled it?
from discord.ui import buttons
Or button not sure if it’s buttons or button
File "C:\Users\GUDDU\Desktop\Program\Projects with my friends\Discord_bot.py", line 3, in <module>
from discord.ui import Button, View
ModuleNotFoundError: No module named 'discord.ui'```
pip install discord.ui
oh
did same error coming
No
no?
@slate swan install dpy 2.0+ from the gitbub repo
pip install -U git+https://github.com/Rapptz/discord.py
ok
Do this @slate swan
Copy and paste it
It will work
Cloning https://github.com/Rapptz/discord.py to c:\users\guddu\appdata\local\temp\pip-req-build-kwt8zcla
ERROR: Error [WinError 2] The system cannot find the file specified while executing command git version
ERROR: Cannot find command 'git' - do you have 'git' installed and in your PATH?
WARNING: You are using pip version 22.0.3; however, version 22.0.4 is available.
You should consider upgrading via the 'C:\Users\GUDDU\AppData\Local\Programs\Python\Python310\python.exe -m pip install --upgrade pip' command.```
and make sure git is installed
Bro that’s done
knew it lol
how to install it?
Sigh bro
oh git
yes git
yeah yeah doing it
any of you know places where they hire discord bot devs ?
No
whatever you want
So I’m Making / commands but I don’t wanna make it certain guilds how would I do it
^ what I mean is I don’t use guilds = “guild id”
you mean
u want to send the reply to which ever server's text channel the command is used in
I want it so if anyone invites bot the slash commands will work in every server
And not just ones with the id In code
dont use default guild parameters then
it will take 1hr for new commands to get added though
sigh why arent their discord servers where you can post adds as a discord bot dev
I saw an add a while back it was crypto related so you would probably have to create those annoying crypto bots. It was on LinkedIn
I think the search I was doing was just python jobs or something basic like that. Hope it helps 🤷♂️
i see ty
@client.command()
async def clear(ctx, limit:int):
await ctx.channel.purge(limit=limit)
await ctx.send(f'{limit} messages have been cleared.')
``` Why this worked but when I typed `!clear 1` it didn't say anything
Guys why everyone ignored me???
AGAIN
I just wrote a message and everyone stopped
how do i fix this
For the second thing use a database that stores what the user wants specifically for the guild
Does @bot.event stop all @bot.command() 's from executing?
import discord
from discord.ext import commands
from discord import guild
from discord_slash import SlashCommand, SlashContext
from discord_slash.utils.manage_commands import create_choice, create_option
import config
client = commands.Bot(command_prefix="?")
slash = SlashCommand(client, sync_commands=True)
@slash.slash(name="slashtest", description="hmmmmm", guild_ids=[957233126818578462])
async def _test(ctx:SlashContext):
await ctx.send("ok")
client.run(config.toke)
Code
tell me the solution anyone
Found the solution you first need to check if message has a meaning / command otherwise it will not execute it py @bot.event async def on_message(message): await bot.process_commands(message) smth..
https://pypi.org/project/discord-py-slash-command/
How to make an option with this library
I tried reading docs but couldn’t find it
Or just use the listen decorator
!d discord.ext.commands.Bot.listen
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.10)").
Example...
Smth should be before process commands
@tawdry bobcathi
@client.command()
async def clear(ctx, amount=5):
await ctx.channel.purge(limit = amount)``` Why this worked but when I typed `!clear 3` it didn't say anything
ur bot prob doesnt have the perms to execute that in the server
change the perms
What
U didnt send anything?
? wdym?
It's only made to purge
is there any way to find APIs that used in a mobile app?
You didn't add any message
Yes
Oh sorry i meant it didn't delete anything
uh
Did it throw an error?
no
Does your other commands work?
yep
Prob u have done any silly mistake
your bot or you probably do not have the permissions or you are trying to input a large number
"!clear 3"
hm should have pinged me
client = commands.Bot(command_prefix="!", activity=activity, status=discord.Status.online)
Show ur full code
wait
!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.
sorry
/Malicious
message intents will be enforced from april 30
they are not to be enabled as of now
Oh
..

Why ppl use os?
What is the use of os.getenv('TOKEN')
os.getenv(key, default=None)```
Return the value of the environment variable *key* if it exists, or *default* if it doesn’t. *key*, *default* and the result are str.
On Unix, keys and values are decoded with [`sys.getfilesystemencoding()`](https://docs.python.org/3/library/sys.html#sys.getfilesystemencoding "sys.getfilesystemencoding") and `'surrogateescape'` error handler. Use [`os.getenvb()`](https://docs.python.org/3/library/os.html#os.getenvb "os.getenvb") if you would like to use a different encoding.
[Availability](https://docs.python.org/3/library/intro.html#availability): most flavors of Unix, Windows.

I'm not sure but I turn on all the perms but still not work
Wait unix has flavours?
yes
Show
wait
Other commands work right?
From what it looks that their only command
yeah
Which command?
all of it except clear
Name any one
suggest command and welcome message
You have a command for a welcome message?
intents
Can the bot see the channel?
yes
Firstly, activity isn't defined and the screenshot you showed us shows that the bot is playing codly? Where did that come from?
I have more code
^
Then show
Do you have on_message listener?
okay wait
intents = discord.Intents.all()
Put this above ur client variable
They said their other commands worked
Hm
@brisk zodiac
okay
And send ss
done
And ur client var will be
client = commands.Bot(command_prefix="!", activity=activity, intents = intents, status=discord.Status.online)
@brisk zodiac
Do this and show ur code
It's error
Traceback (most recent call last):
File "main.py", line 59, in <module>
client.run(token)
File "/home/runner/Welcoming-Bot/venv/lib/python3.8/site-packages/discord/client.py", line 723, in run
return future.result()
File "/home/runner/Welcoming-Bot/venv/lib/python3.8/site-packages/discord/client.py", line 702, in runner
await self.start(*args, **kwargs)
File "/home/runner/Welcoming-Bot/venv/lib/python3.8/site-packages/discord/client.py", line 666, in start
await self.connect(reconnect=reconnect)
File "/home/runner/Welcoming-Bot/venv/lib/python3.8/site-packages/discord/client.py", line 601, in connect
raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
Show code
Meh
okay wait
Just go to that link and tick the member, presence and message intents
Yes lol
Why are you encouraging commands.Bot to be named client exactly? Just wondering
ah i fogot
how do i make a command that that command can be used in a channel?
Im not
They already have client as var
Huh?
like how do i make my command be used in the channel only and not any other
Whole code changed tf
like how do i make my command be used in the channel only and not any other anyone?
Just add a check
channel = bot.get_channel(id)
if ctx.channel == channel:
#do something
else:
#not in the channel you want
sorry
Its the only command i can see
client = commands.Bot(command_prefix = '/')
Omfg name
what
Wahh
As I said on_message is the problem here
Just add await bot.process_commands(message) at the end of on message event
The person u replyed has the same name as me
oh ye lmao
It just give / prefix
Its not a slash command??
it is
@slate swan am i right
oh nvm nvm
^
u mean as in /dino so it will show dino bot commands
U know what are slash commands
Yes
mhm k
????
"Full"
oH
Can I just give him the hastebin link?
Ye
@slate swan
^
yes
Someone have ban and unban code?
!d discord.Guild.ban
await ban(user, *, reason=None, delete_message_days=1)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Bans a user from the guild.
The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
You must have the [`ban_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to do this.
!d discord.Guild.unban
await unban(user, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Unbans a user from the guild.
The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
You must have the [`ban_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to do this.
await ban(*, delete_message_days=1, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Bans this member. Equivalent to [`Guild.ban()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.ban "discord.Guild.ban").
This all?
Or i need to add smth
That's how you ban someone now just making the command is up to you
TypeError: Cannot read properties of null (reading 'click')
at click_date (C:\Users\Admin\Desktop\norg\utilities\other\TG\gen.js:74:13)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async fill_discord (C:\Users\Admin\Desktop\norg\utilities\other\TG\gen.js:88:5)
at async create_accinfos (C:\Users\Admin\Desktop\norg\utilities\other\TG\gen.js:197:5)
at async C:\Users\Admin\Desktop\norg\utilities\other\TG\gen.js:240:21
Anyone?
Is that js
It doesn't belong here. Maybe
Can some1 show me an example of xp system in bots?
Indeed it is
Dump it to some file?
ctx.send(message.embeds[0].description)
I have this where i get the description of the replied embed. But i only want to get the mention User in the description. Someone knows how i do
Should I dump the xp number to some file?
I think he meant 2 separate commands, quite useless to make this kind of "soft ban"
Also don't spoonfeed
@client.command()
async def hello(ctx, args):
await ctx.send("Hello" , components = [Button(label=args, style=1)])```
is something wrong in here? because i when i am typing the command in discord it is neither showing an error nor showing the output
ctx.send() doesn't have component kwarg
you have to subclass discord.ui.View to use buttons
oh
i also tried with view, not working
you can see example like this https://github.com/Rapptz/discord.py/blob/master/examples/views/counter.py
wdu mean
Thx
how do i pass self as arg in cogs when i dont have self in my main method?
wdym... you dont
self represents the instance of the class so you dont actually pass self
uh yeah, in that case, slash commands UI will not be activated
and the slash commands operations
sais i have to pass self
wait is it because im trying to access a command from a cog through main?
when i execute a function imported it just print in the console and not in discord
how can i fix
What Are Slash Commands?
Slash Commands are the exciting way to build and interact with bots on Discord. With Slash Commands, all you have to do is type / and you're ready to use your favourite bot. You can easily see all the commands a bot has, and validation and error handling help you get the command right the first time.
Note: Setting the application's prefix as
/will not activate the Slash Commands User Interface and Server Operations. You will have to register the Slash Commands to the Discord API to use the desired features.
What is the Ideal way of creating Slash Commands for my Bot Application (python)?
Use A Discord API wrapper.
What Wrapper Do I Use?
You can Choose From:
Discord.py
Disnake
Nextcord
Py-Cord
Hikari
How Do I create Slash Commands?
Your Desired API Wrapper Provides you with DOCUMENTATION and EXAMPLES on GITHUB.
A simple search on the web will make it possible to access those.
I am Stuck Creating Slash Commands, What do I do?
Raise an issue on Stack Overflow/Github.
Seek Help in your desired wrapper's Support Server.
Seek Help in Other Suitable Servers.
HELLO
Do you know discord.py slash commands
How do you do options
no 
ik about disnake and nextcord
I heard dpy's slashes are insanely complicated 
No
It’s same as ext
oh well well
idk, havent used
It’s similar to your basic ext command
how can i make the bot to catch text from console and print it in channel
import discord
class MyClient(discord.Client):
async def on_ready(self):
print('Logged on as', self.user)
async def on_message(self, message):
# don't respond to ourselves
if message.author == self.user:
return
if message.content == 'ping':
await message.channel.send('pong')
client = MyClient()
client.run('hidden')```
why bot not launching ?
Bot is launching but
logged on as not showing up
why did you creat a class ?
subclassing
and subclass commands.Bot not Client
commands.Bot is a subclass of Client with commands
I think you should do that
oh I forgot all the "self"
indent is not correct no?
is it important to keep the class ?
await ctx.send(embed = discord.Embed(description = f'"text here', color=0x2ecc71, delete_after=7))
how to set a footer on this?
a footer ? like a description under a title ?
NameError: name 'client' is not defined
@client.event
async def on_ready():
print('Logged on as', self.user)```
yes
await ctx.send(embed = discord.Embed(title = "your title", description = f'"text here', color=0x2ecc71, delete_after=7))```
@proud rain
thanks man
I dont know why you have created a class...
U need to define client
Yes
how?
def client
That’s wrong u didn’t define client
didn't you just send a code about subclassing Client
HUH
What is wrong with this?
this is not it
IndentationError: expected an indented block
this is wrong in every simple way
Why are u sending your code here if its working?
indentation of on_message, on_message not registered as event, client overwritten with non-existing Class
@bot.event / @bot.listen()
Client for these guys
yeah you can do @client.event or @bot.event you choose
wrong naming but acceptable, yes
Hello guys im making a command in my bot of customwheel
What i need in this is to make the bot choose between all the options a user gives. a random one. not by me but the user using the bot
Doesnt really matter. Depends What they choose to call it
anyone can guide me on this one?
import discord
client = commands.Bot(command_prefix='your prefix', intents=intents)
@client.event
async def on_ready():
print('Logged on as', self.user)
async def on_message(self, message):
# don't respond to ourselves
if message.author == self.user:
return
if message.content == 'ping':
await message.channel.send('pong')
client = MyClient()
client.run(token)```
NameError: name 'commands' is not defined
I don't prefer client because it's not a client, it's a bot
!d random.choice
oh yes I forgot
random.choice(seq)```
Return a random element from the non-empty sequence *seq*. If *seq* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError "IndexError").
how is that helpful.. where am i supposed to place it
you were frankly misled
Yes But in reality it doesnt matter.
yeah it doesn't
it should be good
no
bruh
how is the user inputting options?
it shouldn't
tell me why
wdym
i dont understand
.
NameError: name 'intents' is not defined
like how are you getting the options in your command? (in what format)
yeah delete it
intents = intents
NameError: name 'MyClient' is not defined
so much wrong with this
it's your class
Use client not Myclient
How to make interactive message on discord.py
you want to log your bot right ?
exactly
With slash commands
ikr
bruh help us if you are smarter than us but don't say it's wrong without help us bruh
ya'll not helping i'll just google up will be better except chyron but chyron
told everything
won't spoonfeed
yea
U got into this mess Cus u googled and copied without understanding What u were copying
The syntax, random variables,….. 😤
this is NOT good
actually I'm starting to think I should
U cant use my.client of That’s not What u defined in the beggining when setting up the bot
As I said he put random variables syntax off point I don’t think anything is right with code
- name the variable
botwhen instantiatingcommands.Bot - you are overriding
clientat the end, so nowMyClient()will be what client holds
Ur using variables u never defined
oh 6 spaces indents
^
Bottom line there’s nearly every error possible in that code
I feel like u watched many different tutorials and they all used different variables for the same thing
I think so too
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="!", intents=discord.Indents.default())
@bot.listen("on_ready")
async def on_ready():
print('online')
@bot.listen("on_message")
async def on_message(message: discord.Message):
if message.author.bot:
return
bot.run('token')
stop arguing ya'll
thanks Ashley
Good
Perfect
Discord bots is the only thing im not shit at coding
relatable
So this was fun lol
one ping command?
thankfull I wrote "from discord.ext import commands" 🤦♂️
Same I’m shit at everything else
he was trying to subclass so:
class Bot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
...
bot = Bot()
great job
advanced way
Everyone in here should develop games using pygame
🗿
https://pypi.org/project/discord-py-slash-command/
Is there interaction option on these docs I can’t find it
well innit
is it possible to add role to someone when we start by "async def on_message(message) ?
Yes
@bot.command()
async def ping(ctx: commands.Context):
await ctx.send(f"My Ping is {int(bot.latency * 1000)}")

It is
Chyron were you really trying to spoonfeed like that
What person
prodigy
if any(message.author.id) == some_id_here:
# code here
the pep8 typehint aswell
don't be rude pls
he isn't
I'm not
is there a way to run the setup(bot) for cogs without putting it in on_ready?
override setup method
wdym?
setup for cogs is called automatically at load_extension
He’s not being rude if your gonna do discord.py you need a decent grasp of py basics
so instead of adding cogs i should load extensions?
yeah im new btw
yeah
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
I just wanted to help
oh wait he meant that setup
loading extensions is not async, you don't need to import anything and it calls setups for you
ahh thats nice
in dpy 2 it is
I started by this: I guess there are a lot of errors
!d discord.ext.commands.Bot.load_extension
await load_extension(name, *, package=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Loads an extension.
An extension is a python module that contains commands, cogs, or listeners.
An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.
Changed in version 2.0: This method is now a [coroutine](https://docs.python.org/3/glossary.html#term-coroutine "(in Python v3.10)").
nvm yeah load_extension is async
the problem is because i cant start a background task (tasks.loop) in another cog without waiting for on_ready i have to somehow load the cogs before on_ready
burh
async def load_extensions():
#stuff
#run it with bot.loop?
See name input aka interaction how do you do this on discord.py slash commands
Bottom line I’m using ctx rn but I wanna switch to / commands
Is there a way to add a role when I started by "async def on_message" please ?
Bro pls fix the syntax I beg
ik I did errors
Not errors syntax
just want to get a command to add role
if not message.content.startswith("!"): ?
guild id is integer not string
if you want commands, use commands
ik
to hide it
ok thanks for the help...
you don't have to
we can't do anything with the id
@bot.command()
async def hello(ctx):
await ctx.send("Hello!")
this is.... basically what a command is built like
I don't want ctx
You use ctx on commands
you have to get ctx
tbh its the easiest wayy
to add a role ?
^
and you mostly need it
Ctx.add.role
no
Or something I forgot the method
I know that command but without ctx ?
await ctx.author.add_roles()
Ctx is easier
or a member you get
yo boys
Yo
how would i start a tasks loop from a cog
im baffled i cant pass self from main since i dont have self
in __init__
class gif_cog(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.every_10_min.start(self)
like this right?
the loop is every_10_min
yes you do lol
yeah cuz you call it from self
y
__init__ is an instance initializing method
why would you make it a class or static method
yeah I was missunderstandable there
nah
when I'm thinking of something, I don't think that other people can't read my mind

ah ok
well what you can do @hybrid mural is:
class MyCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.my_task.start()
@tasks.loop(seconds=5.0)
async def my_task(self):
...
works now, the problem was that i did a task.before_loop and waited untul bot was ready, while he already was ready
thanks for the help boys
How can I raise my own MissingRequiredArgument?
you might be able to make a custom version of it by subclassing it
or you could use on_command_error and send a custom message when that error occurs
I need it for my error handler and one of the args (Greedy type) doesn't raise it
class CustomMissingArgument(MissingRequiredArgument):
super().__init__(do your stuff)
^
idek when it is even used
!d discord.ext.commands.Greedy
class discord.ext.commands.Greedy```
A special converter that greedily consumes arguments until it can’t. As a consequence of this behaviour, most input errors are silently discarded, since it is used as an indicator of when to stop parsing.
When a parser error is met the greedy converter stops converting, undoes the internal string parsing routine, and continues parsing regularly.
For example, in the following code:
```py
@commands.command()
async def test(ctx, numbers: Greedy[int], reason: str):
await ctx.send("numbers: {}, reason: {}".format(numbers, reason))
``` An invocation of `[p]test 1 2 3 4 5 6 hello` would pass `numbers` with `[1, 2, 3, 4, 5, 6]` and `reason` with `hello`...
ew
* better
most input errors are silently discarded
yeah
why would u
for context: async def command_kick(self, ctx: commands.Context, users: commands.Greedy[disnake.Member], reason: Optional[str]):
it eats up the error
exactly
yeah its greedy
You typically use greedy to make a list of args but in the middle
greedy is too dumb
yeah that's why u don't use it
oh
in your case for sure
If the list of args is last, you just use *args: Type
everything was made to be used
😦
so then how can I make it take more than one user/member?
greedy?
this is my issue xD
I'm out there
why don't you set it to None by default
and check in the command if it's None
c.execute("INSERT INTO olie(caffiene) VALUES(?)", (10000mg,))```
how to test if the ctx message was send on a certain guild to send a message?
this ain't activities
Setting 'Playing' status
await client.change_presence(activity=discord.Game(name="a game"))
Setting 'Streaming' status
await client.change_presence(activity=discord.Streaming(name="My Stream", url=my_twitch_url))
Setting 'Listening' status
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name="a song"))
Setting 'Watching' status
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="a movie"))
client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching,name="test"))```
the wording of that sentence makes my head hurt.
just do the same arg in the constructor
whatching
discord.Client(activity=discord.Activity(type=discord.ActivityType.watching, name="a movie"))
there should be a better way
what ching
i mean for example someone write "test" and before the bot send something like "test worked" he proofs if its the right guild
if not, he says for example "test didn't worked, wrong guild"
hi i want help
if message.guild.id == a guild id you saved:
can I also put ctx instead of message?
yeah
ok nice thanks
@bot.command()
async def преды(ctx, member: discord.Member = None):
cursor.execute("""CREATE TABLE IF NOT EXISTS warning(guild BIGINT, userid BIGINT, warn INT, count INT, reasons VARCHAR)""")
base.commit()
print(1)
global warnings
warnings = cursor.execute("SELECT * FROM warning WHERE userid = ?", (ctx.author.id,)).fetchone()
print("работает")
if member is None:
await ctx.send(f"Проверка по базе данных...\nПроверка прошла.\n{ctx.author.name} У вас {warnings[2]} предупреждений")
else:
await ctx.send(f"Проверка по базе данных...\nПроверка прошла.\n{member.name} У вас {warnings[2]} предупреждений!")
why when a member is mentioned, their warn are shown??
cuz that's what the code does
a good tip to figure out what attributes a things has is python print(str(dir(ctx)))
it's what you wrote
What?
nvmd
wtf how many slash commands do you have
they take up like 1 line
oh you mean literally everything that the commands do
if ctx.guild.id == '0000000000000':
^
IndentationError: unindent does not match any outer indentation level```
@bot.command()
async def преды(ctx, member: discord.Member = None):
cursor.execute("""CREATE TABLE IF NOT EXISTS warning(guild BIGINT, userid BIGINT, warn INT, count INT, reasons VARCHAR)""")
base.commit()
print(1)
global warnings
warnings = cursor.execute("SELECT * FROM warning WHERE userid = ?", (ctx.author.id,)).fetchone()
print("работает")
if member is None:
await ctx.send(f"Проверка по базе данных...\nПроверка прошла.\n{ctx.author.name} У вас {warnings[2]} предупреждений")
else:
await ctx.send(f"Проверка по базе данных...\nПроверка прошла.\n{member.name} У вас {warnings[2]} предупреждений!")
itll be an int not string, and have you put anything after it
why when a member is mentioned, their warn are shown??
ValueError: components must be a WrappedComponent, a list of ActionRow or a list of WrappedComponent
help?
but why does rzwo have 7/8 spaces indents
show code where you're making the components
is it possible that the bot can use server emojis without having nitro?
what is it how to fix it?


