#discord-bots
1 messages ยท Page 1019 of 1
But still can fuck your shit if you don't know how to fix it
Yes
Also you should use this instead
!d discord.ext.commands.Bot.listener
it doesn't work. After this stuff, the bot no longer responds to commands!!!
Are you passing the filepath to that function?
Hi brad
What?
AND THEN HOW TO ADD TO THE FILE THE WORD THAT I WRITE TO THE COMMAND!?
for now I am going to use discord-slash can you tell me what's worng with my code
I don't use 3rd party libs for slash commands
YOU WOULD WRITE THE WORD TO THE FILE
And other stuff
sorry, caps
the library is outdated
what you wrote to chela doesn't work. And here discord.py broken shit
Brad mad ๐
they shifted to interactions.py
That wasn't meant for you
!pip discord-py-interactions
not working
WHAT !?
You'd need to have message intents on
!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 Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, 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.
If you don't already
i have
What's your current code?
i know and it is on
so what, and why tell a person something that doesn't work and is broken!?
No
on_message doesn't take ctx
It's just message
So just use that message object
And delete the message
your_word = ... # returned from your command
with open("your_json_file.json", "a+") as f:
json_data = json.dumps(your_word)
f.write(json_data)
This could be one solution to your problem. Although writing multiple times to a json file can break it pretty easily.
good idea (not for us)
I should be in the esoteric channel
?
and why?
And why what?
why can frequent addition to a file lead to a breakdown ?
The esoteric channel reminds me of the time i tried brainfuck
If you append multiple json data structures to the json file, it can become a mess of indented json objects instead of one cohesive data structure
@supple thorn
Oh you're checking the list
Check if the message content is inside the list
So you have to take care when reading and writing
Not if the list is inside the message content
!pypi better_profanity
I just want to add only bad words or insults to this file
Yes
as a wise old man once said: there's a lib for that
How do i get bitches
or do you think it's better to replace the file with a database?
secrets to the universe? there's a lib for that
A database is better suited for the job, and as linked above, there are some pre-existing libraries that could do the same job without the extra work
god that was sus
I'm already using sqlite3
Oh nice, then you can create a "bad words" entry or something like that, and append your bad words to that column
I just don't quite know yet how to use a database instead of a file, well, how to edit the code correctly
prolly use the api
i haven't used it personally
message = ||fuck||
delete
but
message = ||fuck blabla||
nothing
๐คฆ
=.=
whats this
class Ticket(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label='๐ฉOpen ticket', style=discord.ButtonStyle.blurple, custom_id = 'open-ticket')
async def button_callback(self, button, interaction):
guild = interaction.guild```
AttributeError: 'Button' object has no attribute 'guild'
Well, its a good time to learn! I'd recommend making a standalone function to handle the database reading / writing and then using that in your command to add a word / get a list of the words etc
Please help guys, idk how the interaction is a button
try py if any(i in message.content.lower().replace(' ', '') for i in bad_words): await message.delete()
msg filter problem
@supple thorn
okok
!pypi better_profanity
you did?
Keyword is tried
๐
The order of interaction callback's parameter was switched to (interaction, button) instead of (button, interaction). Here's the commit url: https://github.com/Rapptz/discord.py/commit/968a1f3
so far I have only been able to make sure that warnings are issued for bad words and all this is recorded in the database and after 3 warnings a mutation is issued
Someone else is trying to figure out what i figured out in the esoteric channel
I wish that man the best
๐ imma have a look ig
That sounds like it is quite far along then!
im gonna try to make a package that filters swears
This worked! Thanks a lot man :)
didn't you ask this before
but only one person answer me
Don't they have a api
is what i said
Sounds like a you problem
๐
We can fix that
Do they have a api wrapper?
!pypi topggpy
^
i legit send that :/
hey how do you create a slash command in discord-py-interactions
https://docs.top.gg/api/@reference/
this is the api
i need webhook for that right?
simplejson.errors.JSONDecodeError: Extra data: line 1 column 27 - line 1 column 47 (char 26 - 46)
I understood about the mistake you were talking about
Sent what
discord.app_commands?
the link
Yes i know
hello brad
Haha, yup thats the thing! The way around it is to read all the data in, modify the data, then write it all back to the file. But this can be unstable and slow depending on the file size
how to solve this I already understood just to make a database
Brad always waves menacingly
*more reactions for me to click on *
You would read all of the data from the file as a json object, modify it, then write all of it back to the file
transcript = await chat_exporter.export(channel, set_timezone='CET')
transcript_file = discord.File(io.BytesIO(transcript.encode()),filename=f"{channel.name}.html")```
AttributeError: 'NoneType' object has no attribute 'encode'
Anyone knows why this doesn't work?
ur try-except is outside the function, indent it properly
Depending on how you open the file, you can either replace it or append it or even more depending on the mode.
I just now realize we can't make our own reactions
!with
The with keyword triggers a context manager. Context managers automatically set up and take down data connections, or any other kind of object that implements the magic methods __enter__ and __exit__.
with open("test.txt", "r") as file:
do_things(file)
The above code automatically closes file when the with block exits, so you never have to manually do a file.close(). Most connection types, including file readers and database connections, support this.
For more information, read the official docs, watch Corey Schafer's context manager video, or see PEP 343.
What
Seems like transcript is not getting any value assigned to it
oh wait
๐
or, chat_exporter.export() is returning None
hmm
except has to be on the same level as the try.
ty
#python-discussion and #discord-bots have the reactions disabled because people spamed / abused them (in the past and there have been decisions made on it before my time). And we can't effectively moderate reactions
ur try and except block must be at the same indent level
try:
...
except:
...
valid ^^
try:
...
except:
...
invalid ^^
so it should be like this
yea
Who can make reactions?
imagine opening a json file every message
people with special roles
Which
Only staff helpers<
Staff (helpers +), and maybe partners?
Hello ashley
like devs, yters and boosters etc
Hey Skev
and how to add something there ?
What does bweer mean
They wouldn't give someone who donates to the server extra perms.
Beer with an accent?
Well beer was already taken :3
maybe they dont, they all have that similar blue color so i might've gotten it confused
Is your name enrique
Yes?
What does using spotify feel like
..??
They are clicking on your profile (and your spotify is linked)
ad-less?
I know, I don't hide my name but I don't know why he/she is discussing that here.
But it was so random tough lol
that i agree
good point. @supple thorn don't disclose personal info on others without that user's permission please
embed.set_author(XYZ["name"])
TypeError: Embed.set_author() takes 1 positional argument but 2 were given
XYZ['name'] is literally a string
print(XYZ['name'] = XYZ Information
!d discord.Embed.set_author
set_author(*, name, url=None, icon_url=None)```
Sets the author for the embed content.
This function returns the class instance to allow for fluent-style
chaining.
i also looked at the docs, i came here because i didn't understand the error
Look at the parenthesis and how they are constructed.
(*, name, url=None, icon_url=None)
* < indicating that everything is a keyword argument. And that name here is a required kwarg.
url and icon_url are optional.
right
Do you know how to solve the issue?
ye
Learn what arguments are before using an advanced python library
how do i add custom emoji to a message?
msg = send(...)
await msg.add_reaction("<:emoji_name:emoji_id>") #for static emojis
await msg.add_reaction("<a:emoji_name:emoji_id>") #for animated emojis
add
yea
Not "react"
But it's the same pattern
For
, put !Python
example:
im gonna cry
Add \ before your emoji, send it and copy paste that
<:emoji_name:emoji_id>
^^
you can either get this by putting a backslash before the emoji or put them manually
If you can't send the emoji you can get its id and name
</:kiff:970673345643307088>
Without /
i know
second
Seems like it's not a valid emoji ID
How to add this thing on my script anyone?
Very original at copying a bot ๐
Web one
which thing
Web
See the screenshot
Not really directly related to bots; more like Python and Replit, which is bad
from flask import Flask
from threading import Thread
app = Flask('ok')
@app.route('/')
def home():
return "I'm alive"
def run():
app.run(host='0.0.0.0',port=8080)
def keep_alive():
t = Thread(target=run)
t.start()
I already add this
Again, not directly related to discord bots.
So?
As you can see it's flask
Yes?
So? So this is a topical channel.
um
You can use a help channel, you can get more information in #โ๏ฝhow-to-get-help
Ohh k
i`m send emoji
and
That doesn't give the ID
That gives, most likely, the message ID
oh
๐ณ
how to get ID emoji?
Hmm well, without Nitro it's complicated to explain
ok
Ctrl+Shift+I -> Click on the icon at the top right here
I will try myself
Then hover with the mouse on the emoji
Click on it
You get to a thing like this
And data-id is your emoji ID
970602565244973086
More accurate yep
wait
why not send the emoji and copy the id by right clicking on it.....?
YES, it work
thx so much
No nitro: can't send
Especially animated ones
copy ID message
For static you can just use \:emoji:
well.....
lmao
my friend used the same template
why would you want your serverinfo command to mention every bot in the server ๐
Not so pog
I wonder if you can torture someone with python
Imagining the fbi using python to get intel from the enemy
yeah, fbi is stuck with amd, they need that intel
I want bot status like this anyone?
Hello, how to detect if a member have nitro booster please?
you can't set the bot status to mobile
!d disnake.Member
class disnake.Member```
Represents a Discord member to a [`Guild`](https://docs.disnake.dev/en/latest/api.html#disnake.Guild "disnake.Guild").
This implements a lot of the functionality of [`User`](https://docs.disnake.dev/en/latest/api.html#disnake.User "disnake.User").
x == y Checks if two members are equal. Note that this works with [`User`](https://docs.disnake.dev/en/latest/api.html#disnake.User "disnake.User") instances too.
x != y Checks if two members are not equal. Note that this works with [`User`](https://docs.disnake.dev/en/latest/api.html#disnake.User "disnake.User") instances too.
hash(x) Returns the memberโs hash.
str(x) Returns the memberโs name with the discriminator.
there should something about premium there
So how that guy set?
thanks
it's possible to set a bot's status to online on mobile
but not with discord.py or it's forks
property public_flags```
The publicly available flags the user has.
in discord.js for example you can override the websocket connection parameters
aha @amber bloom there you go
const client = new Discord.Client({ ws: { properties: { $browser: "Discord iOS" }} });```
i'm not aware of such feat with discord.py
What's that?
can someone help me here, usin pycord, tryina make it so my bot lists all servers its on with invites on run
(slap) BAD JS (slap)
Ohh k
didn't you ask this before
and i helped you?
im still fcked ๐
been tryin and tryin lol
thanks ๐
for guild in bot.guilds:
print(f'Invites in {guild}', str(await guild.invites()))```
but isn't that kinda against tos
because in this way, you can find your way in private servers
yo @quaint epoch btw howd u get that date in your bio to be hoverabl with info
aah tysm! i'mma try that
you wanna do that in your bot?
!d disnake.utils.format_dt
disnake.utils.format_dt(dt, /, style='f')```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)"), [`int`](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)") or [`float`](https://docs.python.org/3/library/functions.html#float "(in Python v3.10)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
i usually use a datetime object
<t:19129393>
<t:19129393>
it returns a string like that
Like I tried tagging my @ in bots bio using <@myid> but that never worked
do member/user.mention
oh in your BIO
Ooh Iโmma have to try that when get back on pc ๐ Ty bro
i don't think you can do that
you can't mention ppl in your bios
Ooh Aight
Installed?
Hmm
why are u importing all cogs 
๐ถ
Brother you know how to solve this?
install keep_alive
and use os.listdir or pathlib.Path to load cogs instead of importing
why would you?
Hmm m
i need context on why you would need keep_alive?
isn't it obvious
hmm idk
why would you even need a container?
replit hosting most likely
which is very bad but it works I suppose
yeah
def __init__(self):
I'm confused about this expression. Could anyone explain it to me?
time woyls be a module a d .respond isnt a method and dont use time.sleep it would block your whole bot and not the coro so use asyncio.sleep
!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:
hmm
!d discord.Invite.code
The URL fragment used for the invite.
ure printing the Invite objects, what else did u expect
anyone tried out integrations for their bots yet
seems to not limit it to certain channels 
i mean if your admin ofc youd b able to bypass that ๐
but otherwise it works fine for me with normal members
Ask somewhere else since it isn't related to discors bots
it runs whenever the class is instantiated
for eg
its the function that gets executed when the class is instantiated
class Test:
instances = 0
def __init__(self):
Test.instances += 1
test1 = Test()
test2 = Test()
print(Test.instances)
lmao @slate swan
lets forget that
this prints 2 @atomic wolf
config = {}
with open("stats.json", "r") as f:
config = json.loads(f.read())
async def statusTask():
while True:
for status in config["statuses"]:
if status["type"] == "game":
await client.change_presence(activity=discord.Game(name=status["name"], start=datetime.datetime.now()-datetime.timedelta(status["duration"]), end=datetime.datetime.now()))
if status["type"] == "stream":
await client.change_presence(activity=discord.Streaming(name=status["name"], platform="YouTube", url=status["url"]))
if status["type"] == "competing":
await client.change_presence(activity=discord.Activity(name=status["name"], type=5,))
if status["type"] == "watching":
await client.change_presence(activity=discord.Activity(name=status["name"], type=3,))
if status["type"] == "listening":
await client.change_presence(activity=discord.Activity(name=status["name"], type=2))
await asyncio.sleep(status["delay"])
@client.event
async def on_ready():
print(f"{client.user.name} has connected to Discord.")
client.loop.create_task(statusTask())```
can someone help me?
the error is in the photo
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
format it first
i m new in json stuff
fstrings dont work in json, it only works in python
and its possible to make a server counter in stats using json?
calculate it before and put that in the json
how exactly
the member is returning None

fstrings in json lmao
member is none
which means either _id is None
or there isnt any user with that id
Iโm getting an error:
discord.ext.commands.errors.CommandInvokeError: a Command raised an exception: name โdiscordโ is not defined
I checked the whole damn code there is nothing with it
I have it
Wait
Nvm
I had pasted a code in another file without import discord
Sorry for inconvenience
how can i make self.bot work in button views
@slate swan How do I typehint a Member in the option decorator of a slash command?
for example
@command
@option(name="member", required=False)
and I wanna have the member as a Member object ๐
type=hikari.Member
ohh, thanks
and apologies for the dumb question
and it will popup with a list of members in the server as an autocomplete too :3
me who was stuck with this for days
lmao
oh well, thanks a lot
Developed by: David Powell
Starting Bot
Connecting to Discord API.
Please Wait
[VERSION]{}
Loading Developer Features cog
[โ][Developer Features Cog] Loading Complete
Traceback (most recent call last):
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module>
start(fakepyfile,mainpyfile)
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start
exec(open(mainpyfile).read(), __main__.__dict__)
File "<string>", line 60, in <module>
NameError: name 'mid' is not defined
[Program finished]
error ^
code:
@bot.command(name='msg')
async def msg(ctx, optional_arg: mid = None):
message = await ctx.fetch_message(id=mid)```
how do i fix the mid is not defined?
Is CustomClient a thing like a keyword?
no?
class CustomClient(discord.Client): def __init__(self): super(CustomClient, self).__init__() with open("allykeys.json") as jfile: data = json.load(jfile) self.oauthsecret = data["oauthsecret"] self.oauthtoken = data["oauthtoken"] self.consumerkey = data["consumerkey"] self.api = AllyAPI(self.oauthsecret, self.oauthtoken, self.consumerkey, response_format="json") def exit(self): exit(0)
๐
is it possible to make self.bot work in button views (repost)
ok
wtf is that
class CustomClient(discord.Client):
def __init__(self):
super().__init__(intents=intents) # if you have intents
...
It's like a discord stock info bot code example
I keep forgetting to think about indents.
sorry if its a dumb question but how
huh?
are you subclassing the view?
yup
then
pass
class giveaway(disnake.ui.View):
def __init__(self , bot: commands.Bot):
self.bot = bot
pass the bot into the init function of the class, then pass in the actual bot when you subclass the view class
class MyUwUView(View):
def __init__(self, bot: Bot):
self.bot = bot
@command
await send(view=MyUwUView(bot_instance))
oh i see tysm!
that feeling when you get ignored
:<
oh i didnt see your response im so sorry
np :D
discord.py 2.0 has mostly shorten the syntax ๐
idk, discord.py sucks ๐
ye disnake better
same goes with disnake, I'm against the forks now too
huh?
then ?
nextcord?
dont
why not?
class CustomClient(discord.Client): def __init__(self): super(CustomClient, self).__init__() with open("allykeys.json") as jfile: data = json.load(jfile) self.oauthsecret = data["oauthsecret"] self.oauthtoken = data["oauthtoken"] self.consumerkey = data["consumerkey"] self.api = AllyAPI(self.oauthsecret, self.oauthtoken, self.consumerkey, response_format="json") def exit(self): exit(0)
idk much about hikari i mean why u choose it, reason
i was wondering if def __init__(self): is a subclass of CustomClient
Ashley's used to hikari being bullied so she just answers why not
and then hence the use of the super keyword
probably
its better than dpy at least
idk if i did it right but
class verykoolview(discord.ui.View):
def __init__(self, bot:commands.Bot, *, timeout=None):
self.bot = bot
super().__init__(timeout=timeout)
and i got an error
Traceback (most recent call last):
File "/home/runner/pity/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1325, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/pity/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 948, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/home/runner/pity/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 209, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: __init__() missing 1 required positional argument: 'bot'
verykoolview(bot instance)
you need to pass in the bot instance when you instantiate it
OH
bot.load_extension('noob')
def setup(bot: commands.Bot):
bot.add_cog(noob(bot))
load_extension only calls setup
it worked tysm guys
import time, webbrowser, pyttsx3, discord
from discord import user, message
from discord.ext.commands import bot
TOKEN = 'SDF154s5df415D444'
client = discord.Client()
@client.event
async def on_ready():
print('botloggedin as {0.user}'.format(client))
@client.event
async def on_message(message):
username = str(message.author).split('#')[0]
user_message = str(message.content)
channel = str(message.channel.name)
print('botloggedin as {0.user}'.format(client))
if message.channel.name == 'general':
if user_message.lower() == '!isrunning':
await message.channel.send("The bot is currently running")
return
client.run(TOKEN)
Why doesnt this work?
no errors btw
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 Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, 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.
why intents dont raise error
Because it doesn't make sense
..
You just don't get the message content in that case
And for others you don't get the even dispatched
Ik the api does return an error it's just some of the forks
API doesn't return an error at all.
I'm 80% sure I saw an intent error already
It doesn't dispatch the event or doesn't give the content field to the message
When Intents first dropped
Well interesting
There is an error when you enable a privileged intent with code and you didn't enable it in the developer portal, yes.
Them that's what I probably did
But not an error because you're trying to access .content or catch the dispatched events, doesn't make any sense
CUz when they came and caused an uproar with the new intents I just enabled them locally and saw the error that I had to enable em
Yeah that's most likely what you've got
Ahh j understand
Indeed, I've had this name set here since I joined the server back in 2020
__init__ is to initialise the obj's class
if you subclass, by calling super().__init__(*args, **kwargs) you are instantiating the object from the original inheritance
so it's a way of making an object have the fields of the higher class despite being originally defined on a lower one?
Hey @marsh thorn! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discordapp.com/developers/applications/me
Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!
it didnt have a real token lol
Just leave the token field blank
import time, webbrowser, pyttsx3, discord
from discord import user, message, Intents
TOKEN = ''
client = discord.Client()
intents = Intents.default()
intents.members = True
@client.event
async def on_ready():
print('botloggedin as {0.user}'.format(client))
@client.event
async def on_message(message):
username = str(message.author).split('#')[0]
user_message = str(message.content)
channel = str(message.channel.name)
print('botloggedin as {0.user}'.format(client))
if message.channel.name == 'general':
if user_message.lower() == '!isrunning':
await message.channel.send("The Bot is currently running")
return
client.run(TOKEN)
Why doesnt this work?
fyi you can just use message.author.name
ye ik this is just good to learn for bigger projects
i can see that you are trying to get message.author's name from ```py
username = str(message.author).split('#')[0]
and no need to cast message.content (already a string) to a string, likewise for message.channel.name
what?
like if i have more refrences
what doesnt work
any errors?
no errors it just completly doesnt work
nah i dont think that's necessary
it doesnt hurt to type a few more characters
u can simple do message.author.name
anything in your console
yes, message.author is an instance of Member
property name```
Equivalent to [`User.name`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.name "discord.User.name")
nope
im saying not asking
question mark tells me otherwise
..
Please read the message from the bot again
alr
There are a few things you're missing
- Actually use the variable
intents, right now you're doing nothing with it - Use
Botand notClient, you need to make proper imports which are in the bot's message
ah alr ima try to do that
import time, webbrowser, pyttsx3, discord
from discord import user, message, Intents
from discord.ext import commands
TOKEN = ''
client = discord.Client()
bot = commands.Bot(command_prefix="!", intents=Intents)
intents = Intents.default()
intents.members = True
@bot.event
async def on_ready():
print('botloggedin as {0.user}'.format(client))
@client.event
async def on_message(message):
username = str(message.author).split('#')[0]
user_message = str(message.content)
channel = str(message.channel.name)
print('botloggedin as {0.user}'.format(client))
if message.channel.name == 'general':
if user_message.lower() == '!isrunning':
await message.channel.send("The Bot is currently running")
return
client.run(TOKEN)
like this?
No
Stop using Client
And this shows your bot will actually never start
It's indented wrongly
oh alr so all clients should be bot
whats wrong with the indent?
Correct
Ignoring exception in view <reqs2 timeout=30 children=2> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Invites' emoji=None row=None>:
Traceback (most recent call last):
File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\disnake\ui\view.py", line 370, in _scheduled_task
await item.callback(interaction)
File "c:\Users\hp\Desktop\bot\giveaway.py", line 343, in but11
await interaction.response.send_modal(modal=MyModal(self.bot,"Invites Required"))
File "c:\Users\hp\Desktop\bot\giveaway.py", line 271, in __init__
super().__init__(
File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\disnake\ui\modal.py", line 81, in __init__
raise ValueError("Maximum number of components exceeded.")
ValueError: Maximum number of components exceeded.
``` hm?
You're executing client.run in the on_message event
def x():
yes()
something()
def x():
yes()
something()
This is not the same
You have the version above, it should be the version below
@commands.command(name="hot",help="Sends hot posts from reddit")
async def hot(self,ctx,subreddit:str):
submissions = self.reddit.subreddit(subreddit).hot()
post_to_pick = random.randint(1, 10)
for i in range(0, post_to_pick):
submission = next(x for x in submissions if not x.stickied)
await ctx.send(submission.url)```
coroutine function has no attribute hot
Help
import time, webbrowser, pyttsx3, discord
from discord import user, message, Intents
from discord.ext import commands
TOKEN = ''
client = discord.Client()
bot = commands.Bot(command_prefix="!", intents=Intents)
intents = Intents.default()
intents.members = True
@bot.event
async def on_ready():
print(f'Logged in as {bot.user}')
@bot.event
async def on_message(message):
username = str(message.author.name)
user_message = str(message.content)
channel = str(message.channel.name)
print('botloggedin as {0.user}'.format(client))
if message.channel.name == 'general':
if user_message.lower() == '!isrunning':
await message.channel.send("The Bot is currently running")
bot.run(TOKEN)
Error says all, no?
Maximum number of components exceeded.
lemme try that
you have too many components in your modal
kinda like
Won't help https://i.imgur.com/KRxFbjZ.png
Still running the bot inside the function, which is not what you want
uh
embed = disnake.Embed()
embed.add_field()
embed.add_field()
embed.add_field()
embed.add_field()
embed.add_field()
something like that
i know
Fields are not components
its an example...
yeah
How much maximum can I add
what
oh i edited it on discord
didnt see the indent
import time, webbrowser, pyttsx3, discord
from discord import user, message, Intents
from discord.ext import commands
TOKEN = ''
bot = commands.Bot(command_prefix="!", intents=Intents)
intents = Intents.default()
intents.members = True
@bot.event
async def on_ready():
print(f'Logged in as {bot.user}')
@bot.event
async def on_message(message):
username = str(message.author.name)
user_message = str(message.content)
channel = str(message.channel.name)
print('botloggedin as {0.user}'.format(bot))
if message.channel.name == 'general':
if user_message.lower() == '!isrunning':
await message.channel.send("The Bot is currently running")
bot.run(TOKEN)
is this correct?
Try it
import time, webbrowser, pyttsx3, discord
from discord import user, message, Intents
from discord.ext import commands
TOKEN = ""
client = discord.Client()
bot = commands.Bot(command_prefix="!", intents=Intents)
intents = Intents.default()
intents.members = True
@bot.event
async def on_ready():
print(f"Logged in as {bot.user}")
@bot.event
async def on_message(message):
username = str(message.author.name)
user_message = str(message.content)
channel = str(message.channel.name)
print("botloggedin as {0.user}".format(client))
if message.channel.name == "general":
if user_message.lower() == "!isrunning":
await message.channel.send("The Bot is currently running")
bot.run(TOKEN)
Remove client=...
Pass actual intents to the bot
TOKEN = ""
intents = Intents.default()
intents.messages = True
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
No idea, might want to ask in the discord.gg/discord-developers server
.
eyyy it works
Ok
Nice
ty guys
np
is there an event to see when a member is banned?
discord.on_member_ban(guild, user)```
Called when user gets banned from a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This requires [`Intents.bans`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.bans "discord.Intents.bans") to be enabled.
:(
kek
That doesn't exist
alr
๐ฉ
I got first but...
lmao
Your program is already running, stop it first
Xd done

Does anyone have any example to make a welcome image with PIL?
I can't seem to figure it out
bow do i check if a member is timed out, i.e updated (on_member_update does not look for timeouts)
Huh it isn't triggered?
disnake.on_member_update(before, after)```
Called when a [`Member`](https://docs.disnake.dev/en/latest/api.html#disnake.Member "disnake.Member") updates their profile.
This is called when one or more of the following things change:
โข nickname
โข roles
โข pending...
Prolly a bug in the Discord API
well, im going to try it
Hey hunter how are u ๐
@pliant gulch u got any insight on this?
Hi
hi
Hello ๐
member return none
use member = bot.get_user(id) or await bot.fetch_user(id)
It should be dispatching GUILD_MEMBER_UPDATE because timeout endpoint is really just PATCH guilds/guild_id/members/user_id
AttributeError: 'Member' object has no attribute 'avatar_url_as'
I am trying to make welcome message in PIL
how did you check it in the on_member_update event?
yep its a coroutine
nope, checked it rn
the docs say it doesn't include timeouts, but it does in the api
try avatar.url
ยฏ_(ใ)_/ยฏ
notice the "how"
oh i just created an on_member_update event rn
and it ran every time i muted someone
muted? or timed out
timed out
so the event works...
yes
coroutines are functions which you need to await
@quaint epoch did u test the event?
yes
And it isn't dispatched for timeout? @quaint epoch
nope it is
So it's dispatching?
mhm
๐
it's in my bookmarks, it's going to stay there
bot = commands.Bot("beta ",test_guilds=[966350034822135878], sync_commands=True, case_insensitive=True, intents=intents, strip_after_prefix=True)
@bot.slash_command(description="Responds with the user ID.")
async def userid(inter, user: disnake.Member):
await inter.response.send_message(user.id, ephemeral=True)
Hey, I'm not sure if I just changed something, but this worked 10min ago, and now it just stopped working. Does someone see something wrong?
There is no command_prefix set.
I'm using disnake, it's working without that. The prefix is working fine, I just don't get the slash command shown for some reason anymore
!d discord.ext.tasks.Loop.next_iteration
property next_iteration```
When the next iteration of the loop will occur.
New in version 1.3.
You got an error?
A loop.
Combine it with a database and you're ready.
Nope, the bot normally runs, everything works, the prefix also works normal but for some reason it just doesn't show me the slash command, as said it did 10 min ago
What did you change?
I just removed the help command as I'm currently rewriting my old bot, then it stopped working
If you reverse that it works again?
I just saw in the docs this exists:
sync_commands_debug=True
I'm gonna try that real quick
nope, already tried
https://i.imgur.com/d6uHqIL.png
Still doesn't work, Ig it finishes it as it's loaded?
!d discord.Message.add_reaction
await add_reaction(emoji, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Adds a reaction to the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/master/api.html#discord.Emoji "discord.Emoji")...
my_msg = Interaction
what
I haven't used the library in a while but I guess if you want to add reaction, then you should "reply" instead of "respond"?
you oversaw the error
By the way hoomans, what is this rate limit thingy?
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
bruh
just to be safe
429s/ratelimits are where you send too many requests to the api in a certain period of time, so the wrapper/api temporarily bans you from sending more
like spamming d in a server, eventually discord will tell you to be less spicy, which is the ui version of ratelimiting
Anyway, so my bot was temporarily restricted from using the discord API. When I checked the error, it was because of payload of that raw_reaction_add thingy.
kek
I can send my code if you want but like how do I get rid of that?
well, if it is because of the payload i can't do anything
you'll have to wait until the ratelimit is over
Just check once more if this code is badly designed please.
@bot.event
async def on_raw_reaction_add(payload):
DO = False
message = await bot.get_channel(payload.channel_id).fetch_message(payload.message_id)
if message.author.id != 933372954589401158:
return
emb = message.embeds[0]
if payload.member.id == int(emb.footer.text[5:]):
_reacts = []
for i in (reacts := message.reactions):
if i.me:
if i.emoji == payload.emoji:
_special_emoji = str(i.emoji)
DO = True
else:
_reacts.append(str(i.emoji))
if DO:
await message.delete()
new_emb = Embed(
title = "Your remaining tasks in the to-do list:-",
colour = payload.member.colour
)
new_emb.set_author(name = payload.member.name, icon_url = payload.member.avatar_url)
new_emb.set_footer(text = f"ID:- {payload.member.id}")
new_emb.set_thumbnail(url = payload.member.avatar_url)
for fie in emb.fields:
if fie.name.startswith(_special_emoji):
new_emb.add_field(name = f"~~{fie.name}~~", value = '\u200b', inline = False)
else:
new_emb.add_field(name = fie.name, value = '\u200b', inline = False)
_rmsg = await message.channel.send(embed = new_emb)
if not _reacts:
await message.channel.send(f"Congrats <@{payload.member.id}>! You have finished all your tasks :partying_face:")
return
for i in _reacts:
await _rmsg.add_reaction(i)
I guess the code is too confusing especially without any initial detail
. Anyway, thanks HRLO.
Ok so,
@bot.slash_command(description="hi")
async def hi(inter):
await inter.response.send_message(f"hi {inter.author}")
@bot.slash_command(description="Developer command.")
async def reloadbot(inter):
if inter.author.id == 703671503954378782:
embed = disnake.Embed(title="Sucessfully reloaded bot!", description=f"The cog {cog} has been successfully reloaded.", color=disnake.Colour.green())
for filename in os.istdir("./cogs"):
if filename.endswith(".py"):
bot.load_extension(f"cogs.{filename[:-3]}")
await inter.response.send_message(embed=embed, ephemeral=True)
else:
await inter.response.send_message("a")
For some reason the upper slash command "hi" is working fine, but the other one doesn't. It doesn't even get shown for some reason.
with the new update of text channels inside a voice channel
how do u get the text channel?
what
text channels inside voice....?
here there are none i think
how will it work when it isnt even showing up-
try adding the guilds_ids kwarg
my_msg is already a Message object whih has no attribute as message
Doesn't change anything, I do have the test guilds set up:
bot = commands.Bot(command_prefix="beta ", test_guilds=[966350034822135878], sync_commands=True, case_insensitive=True, intents=intents, strip_after_prefix=True)
bot.remove_command("help")
The "hi" slash command is showing up, the other one isn't that's my problem
my_msg.add_...
weird
Yeah, I kinda figured it out, a disnake developer told me that it's an API bug due the discord update or something, I reinstalled it and now it works. Anyways, thanks for trying to help
why do my buttons stop working after like 5 minutes on the same message?
Could you show your implementation of those buttons
Most likely due to timeout set on view
What's the difference between asyncio.sleep() & time.sleep()?
Why do we need asynchronous programming?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!
Non blocking?
Read the embed above
Default timeout of View is 180 seconds, to ignore it, use View(timeout=None) and for this case I recommend using persistent views
Also it's better to subclass your views cause that way the code looks cleaner
@slate swan dpy 2.0?
@slate swan what is the type of ctx
From API
Discord.py is out of support, so stuff may not work
wdym?
discord.py was unarchived a month (or more?) ago
they have a channel of dev updates that you can follow on their server: https://discord.gg/dpy
@slate swan print(type(ctx))
Issue is not with permissions
Wrong also this is not dpy
in discord.py version 1.7.3 is it possible to make commands that will do something for a certain amount of time ?
that didnt fix it :/
Why?
what dpy version u using
@commands.command()
@commands.has_permissions(manage_channels=True)
async def kick(self, ctx: commands.Context, user: Either[disnake.Member, str], *, reason=None):
if isinstance(user, str):
for member in ctx.guild.members:
if user in member.name:
await ctx.guild.kick(member)
if reason != None:
embed = disnake.Embed(
description=f"""{user.mention} has been kicked.
Reason:
{reason}
""",
)
await ctx.channel.send(embed=embed)
embed = disnake.Embed(
description=f"""
You have been kicked from {ctx.guild.name}
Reason:
{reason}
"""
)
await disnake.DMChannel.send(user, embed=embed)
else:
embed = disnake.Embed(description=f"{user.mention} has been kicked.")
await ctx.channel.send(embed=embed)
break
else:
embed = disnake.Embed(description="User Not Found Onii Chan!")
elif isinstance(user, disnake.Member):
await ctx.guild.kick(user)
if reason != None:
embed = disnake.Embed(
description=f"""{user.mention} has been kicked.
Reason:
{reason}
""",
)
await ctx.channel.send(embed=embed)
embed = disnake.Embed(
description=f"""
You have been kicked from {ctx.guild.name}
Reason:
{reason}
"""
)
await disnake.DMChannel.send(user, embed=embed)
else:
embed = disnake.Embed(description=f"{user.mention} has been kicked.")
await ctx.channel.send(embed=embed)
!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.
its not that long ;/
It is
yes but it's glitching out due to discord escape characters
so just put it in the paste service, takes like 10 seconds to do so
also yeah, indentation is way messed up on discord
oh yeah
k
i wanna be able to do something like
?kick nyx
without mentioning
how to set security level for serverinfo?
you just check a role or something because its definitely not the accounts security level as it would be unsafe
thats the servers moderation level?
yea
!d discord.Guild.verification_level
The guildโs verification level.
nvm what i said as its a guild
thx
i thought it was an account shouldve seen the invoke message
!d discord.Message.mentions
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...
hmm
or just have a member argument if you want it to take a member object
how to mark the number of people with a certain status?
yeah
yep
If so then ^
the converter should work yes
how to mark the number of people with a certain status?
i want it to be a member object if its a mention
you would have to iterate thru guild.members and check their status.
and a string if its a string
wdym?
typing.Union```
Union type; `Union[X, Y]` is equivalent to `X | Y` and means either X or Y.
To define a union, use e.g. `Union[int, str]` or the shorthand `int | str`. Using that shorthand is recommended. Details...
i did
it would look like py async def command(ctx,arg: typing.Union[Member. str]): ...
whats that
yeah i used it
check the pep^
but
4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.
how to make the bot delete its message 30 seconds after sending ?
await send("stuff", delete_after=30)
@slate swan aren 't you tired of writing the same thing ?
not really
@bot.command()
async def test(ctx: commands.Context):
msg = await ctx.channel.send("Ok")
await asyncio.sleep(30)
await msg.delete()
oh ;/
bro
bro
ctx.channel and .sleep๐ฟ
you know that the member converter convers the name and ids as well right?
yeah
but lets say i wanted to do
?kick sar
why do a incheck though
for how long have yall been programming ?
and sarry gets kicked
curious
my friend wants to be able to do pass a bit of their name in
about one year and 2 months
2 months
ah nicee, keep on goin
actually less cuz of exams
2 years, 5 months of serious practice
oh wow
ty ๐
doesnt that make me young noob ๐ฒ
yes
๐ค
@regal pulsar@slate swan@slate swan thanks
np
bro you used Either, not Union
nah
they are different things
๐ why
anyways, what's the issue?
your command would need member intents in cause you didnt add it already
not sure how to go about it in general
if you mention someone i want a Member object
if you just pass in a string it should stay a string
no because the disnake.Member typehint is their first
the converter just parses the string for a snowflake or a snowflake inside of the mention format and it makes it an object
i mean yeah it would be an object as it would return that since if the converter so union is probably the best if sometimes the member object wont be passed an a word would be passed
hmm
is it possible to make a temporary command in this way ? for example , mute or assigning a role for a while ??
or what if i dont typehint
yeah
simply use timeouts
it will be a string
my old mute command if you want it
why spoonfeed
yeah
just give him the coroutine that wraps the endpoint
then i try to get a Member object with .get
!d discord.Member.timeout
await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Applies a time out to a member until the specified date time or for the
given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.10)").
You must have the [`moderate_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") permission to
use this...
how exactly does that work
it works in 3.7 too
ye im on 3.10.4 iirc
its just bitwise or
given that you need to import annotations from future
oh
yeah
with annotations it wouldnt matter what py version
ofc it would as yoy need to import the stlib
*3.6+
@regal pulsar thanks
np
yes but it can still be used in 3.6+
this will only work for mute. But not for issuing a role for a while
its this easy
from __future__ import annotations
add a space or get recked
lol
slow
i already did
idk sarthak said it does idk the exact version lol
working in 3.7 too
I thought __future__.annotations was added in 3.7, not 3.6
my bad
not what i said bozo
now if only i knew what you were talking about ๐
๐ฟ
https://docs.python.org/3.7/library/__future__.html yes it is 3.7, you don't see it in any previous versions
that acts like a Union
i see
no
it can be used in other things and not ony type hint
what did you said
its literally the same thing
its just bitwise or
pipes are cool
lol
can someone tell me what this is
The return annotation
A annotation
the ->
Denoting that that method, returns None
no idea , never seen it in python tbh
ik its something from JS but not sure
i see it everywhere
!e ```py
def foo() -> str:
return "bar"
def baz() -> None:
...
@pliant gulch :warning: Your eval job has completed with return code 0.
[No output]
wait what ๐
You see it a lot in well written code
-> str because it returns "bar", which is a str, then -> None because that one returns None
Good python programmers type/annotate their code

but what does it mean tho? ive never even heard of it and ive been programming for some solid months
He just said above
It's for type safety
Yes, you want to know the types of your variables, etc
Yea.
It's good to know them, and it stops a lot of problems before they happen
not only typehints* it can be used in other things aswell
is it something sorta like a comment or ?
Yes it's like a comment
print func in python
ahhh
no its just for your interpreter to understand types
its sorta like a comment ig
The interpreter doesn't parse annotations at all
doesnt it do that on its own tho
editor sorry
ah
i see
I guess unless you count like __annotations__
sometimes you editor doesnt know what i.e and arguments type is gonna be so devs annotate them so the editor knows the types
yeah
thats actually why i started typehinting
its quite useful without your editor showing its unknown
and sometimes depending on the types the editor wont highlight the syntax of methods i.e since it doesnt knoe the type
A fellow ayu theme user?
just get good and work without the intellisense. All that matters is runtime.
plus
Mi gusta
that's not related to JS, in javascript it means something else
i cant live without this
yea i know, i was just referring that the only place i had seen -> being used was in js and nowhere else but i guess its a thing in python as well
what colour scheme are ya using?
!e ```py
from future import annotations
@type.call
class annotations:
def setitem(self, name: str, value: str) -> None:
print(name, value)
Foo: bar
Looks liike ayu mirage
@pliant gulch :white_check_mark: Your eval job has completed with return code 0.
Foo bar
ok?
Saying or operator is equivalent to typing.Union is miss-leading imo
You should just reference it as a union between the types, operator makes it sound like it does an operation
@commands.command()
async def ping(self, ctx):
message = await embed.add_field(name="`Pinging...`")
await embed.add_field(name=f"**Latency is** ``{round(self.bot.latency * 1000)}``**ms**")
Can't rmr the last time I touched Union after they allowed us to do X | Y in 3.10
Correct?
lmao
Optional[]?
i never touched Union๐ณ
Anyone?
it can be the type given or none basically
ah
I've always hated the typing module
dont you use it allot๐ฟ
I just want a non-library way to type hint ๐
wait
yeah i agree
I only use it cause I'm forced to, like before when list wasn't generic
Now I'm waiting for the callable typehints to be passed in that pep, () -> None
or do i have it completely wrong
it would be nice to have Callable i.e built in without importing typing ๐
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
whats Callable ๐
That already exists with typing_extensions
a function
You only really need self in causes of generics anyways so, most people won't be using them
its just the type lol
No?
yeah what does it do
to show you the api wrapper
i've gotta use another account to test it