#discord-bots
1 messages · Page 982 of 1
i think its a programming language
Please show the full traceback, every part of the traceback is always helpful, don't crop it.
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
import discord
import os
client = discord.Client()
@client.event
async def on_ready():
print("I'm in")
print(client.user)
@client.event
async def on_message(message):
if message.author != client.user:
await message.channel.send(message.content[::-1])
token = os.environ.get("DISCORD_BOT_SECRET")
client.run(token)```(https://paste.pythondiscord.com/sadazuvulo)
@visual island
copy the text here
and send the link
Traceback (most recent call last):
File "main.py", line 17, in <module>
client.run(token)
!traceback Full traceback would look like this.
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
@bot.command()
@commands.has_any_role(692760082085183519, 940008547993927691, 863878825376743475, 902292952381001779, 863879069253894166, 902292952381001779, 863879304110276668, 940008547993927691)
async def пред(ctx, member: discord.Member = None, *, reason = 'Отсутствует'):
print(45)
cursor.execute("""CREATE TABLE IF NOT EXISTS warning(guild_id BIGINT, user_id BIGINT, warn INT, count INT, moderator_id BIGINT, reasons VARCHAR)""")
base.commit()
print(1)
warnings = cursor.execute("SELECT * FROM warning WHERE user_id = ? AND guild_id = ?", (member.id,ctx.guild.id)).fetchone()
print("работает")
if member is None:
await ctx.send("Выберите участника")
return
if warnings is None:
cursor.execute('INSERT INTO warning(guild_id, user_id, warn, count, moderator_id, reasons) VALUES(?, ?, ?, ?, ?, ?)', (ctx.guild.id,member.id,0,1,ctx.author.id,'Отсутствует'))
base.commit()
print(2222)
cursor.execute(f'UPDATE warning SET warn = warn + 1 WHERE user_id = ? AND guild_id = ?', (member.id, ctx.guild.id))
base.commit()
await ctx.send(f"**{ctx.author.name}** Выдал предупреждение #{warnings[2]} {member} (случай # ) {reason}")
else:
cursor.execute(f'UPDATE warning SET warn = warn + 1 WHERE user_id = ? AND guild_id = ?', (member.id, ctx.guild.id))
base.commit()
await ctx.send(f"**{ctx.author.name}** Выдал предупреждение #{warnings[2]} {member} (случай # ) {reason}")
how to make it so that if the reason is not specified, then Отсутствуетis not written in the chat?
bot = commands.Bot(command_prefix = 'rpm ', case_insensitive=True)
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.
is the case_insensitive = True not working anymore
That's because the client doesn t represent a discord Bot, but the application (the one created in the dev portal)
With the application you decide what you want to do with it, a bot, a game, etc
PUHAHAHAHAHA I LAUGH
!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.
You are rate limited
use this link
._.
it works, why?
Probably you have tried to make some bot actions in a short time
10 years later(when my father comes back)
does it make Rpm work?
RPM RpM rPM these kinds
they should work also right?
yeah
but its not working
bot = commands.Bot(command_prefix = 'rpm ', case_insensitive=True)
how did you invoke it?
errors?
code?
no error
case_insensitive is for commands not prefix
blocked? ;-;
but no output when i use the prefix as Rpm
forever?
oo so i need to type it manually?
yeah although there is an example of case insensitive prefix, but it's kinda complicated
stick to the traditional method
fallback = os.urandom(32).hex()
prefixes = ['pls', 'pls ']
def get_prefix(bot, msg):
comp = re.compile("^(" + "|".join(map(re.escape, prefixes)) + ").*", flags=re.I)
match = comp.match(msg.content)
if match is not None:
return match.group(1)
return fallback
bot = Bot(command_prefix=get_prefix)
```
Read the exception
gg
im crying just by reading this
what in tarnation is this
some regex shit
did you just install 2.0
hm
are you on discord.py 2.0
because there are two possibilities:
- you just installed 2.0 and your linter didnt refresh
- you didnt even install 2.0 hence discord.ui isnt a thing
Is it possible for the bot to do:
,msguild 123456789... hello
This should send the hello to the server with this guild id
pip install git+https://github.com/Rapptz/discord.py
Reply with ping
you could have a argument which typehints to discord.Guild and then another arg for message
error
wait you cant just message a guild
you can only message in a channel of a guild
Currently I use a command (send to all guilds) it sends to the channel on top
I’m fine with that
Yea that’s what I mean
cuz you didnt import os and what the hell is config
danny's bot has a GlobalChannel converter https://github.com/Rapptz/RoboDanny/blob/rewrite/cogs/admin.py#L65-L79
because your not on 2.0 as i said
2bad4u
you cant install 2.0 on replit afaik
Idk why but whenever I leave a non required text box empty in my modal it raises
Ignoring exception in modal <ApplicationModal timeout=None children=5>:Traceback (most recent call last):
File "/data/data/com.termux/files/home/codes/otaku/venv/lib/python3.10/site-packages/discord/ui/modal.py", line 187, in _scheduled_task await self.on_submit(interaction)
File "/data/data/com.termux/files/home/codes/otaku/extensions/applications/apply.py", line 69, in on_submit
await channel.send(embed=application(interaction.user, self.responses)) File "/data/data/com.termux/files/home/codes/otaku/venv/lib/python3.10/site-packages/discord/abc.py", line 1503, in send data = await state.http.send_message(channel.id, params=params) File "/data/data/com.termux/files/home/codes/otaku/venv/lib/python3.10/site-packages/discord/http.py", line 501, in request raise HTTPException(response, data) discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body In embeds.0.fields.4.value: This field is required
Oh
because you cant add spaces to the name when running a file from the cli
it will take it as the next argument
How do I make welcome messages in discord.py
@slate swan
@slate swan try now
Wait I'll try
Idk
It works for me fine
Ig get rid of the parentheses
Get rid of ( ) from your file name
first of all you store the ids of welcome channels set by a user with permissions in a database (mongoDB [json-based], SQLite, PostgreSQL, MySQL, etc.), then you use the on_member_join event to see which member joined which guild
''' an example of the event '''
@Bot.listen("on_member_join")
async def check_member_join(member: discord.Member):
''' attributes and methods of "member" are the same as that of a Member '''
Hmm
Wait it'll this time
@slate swan change the name of the file to select_menu.py
and run the following command:
python select_menu.py
Try this python Select\ Menu\ \(Not\ done\ yet\).py
It will work for sure
?
Stay happy
Lol
Yes
funny
Like a while ago
no-
You can fix that
Bruhh
how to get channel id when i pass in a command in that perticular channel
ctx.channel.id
The channel ID.
This module provides access to the select() and poll() functions available in most operating systems, devpoll() available on Solaris and derivatives, epoll() available on Linux 2.5+ and kqueue() available on most BSD. Note that on Windows, it only works for sockets; on other operating systems, it also works for other file types (in particular, on Unix, it works on pipes). It cannot be used on regular files to determine whether a file has grown since it was last read.
Note
The selectors module allows high-level and efficient I/O multiplexing, built upon the select module primitives. Users are encouraged to use the selectors module instead, unless they want precise control over the OS-level primitives used.
This will get the id of the channel where the command was used in
Are you asking people if they have a select menu so you can copy it
@client.event
async def on_message(ctx):
print(f"{ctx.channel}: {ctx.author}: {ctx.author.name}: {ctx.content}")
if "python" in str(ctx.content.lower()):
post = {"_id": ctx.author.id, "score": 1}
collection.insert_one(post)
await ctx.channel.send('hi')```
This is my event
on_message doesn't take ctx
message?
You should name it message so people don't get confused
yes
I should try that?
You named it ctx which is confusing
Because it takes message
It's just a name but you still should practice good naming conventions
But its Printing everything but the data isn't getting saved in my db
how do you know it isnt getting saved
Does the if statement trigger?
They can check
Like literally check on the mongodb website
refresh the website
Hello ashley
Heya Skev

i know that?
Coke slushee taste good
ew
Then why'd you ask
im not asking that literally
i meant "how are you so sure bout it"
Does the if statement trigger or no?
Wait are you using mongodb without motor?
they used eyes
Blocking
Motor?
Yeah
It's so that mongodb is not blocking
Makes it async
It's an async mongodb driver
Since using mongodb on it's own makes it blocking
Which freezes your entire bot until that certain task is finished
It's like
Async you have two arms to do things sync you only have one arm
So i have to install it?
If you want to make mongodb not blocking then yes
How do i do it?
!pypi motor
It should just be pip install motor
i know its stupid but
Ohk
Why do you have 3 x
dont worry about that
Is aiosqlite3 a good database for a leveling system?
Yeah
@commands.command(name = "addc", help = "Adds the channel to send welcome messages")
async def addc(self,ctx):
channel_id = []
id = ctx.channel.id
channel_id.append(id)
await ctx.send("You have added this channel to send welcome messages")```
You were using json? 😔
What's the problem?
No I use json for some things
Bro
But a database will be way better for this
the channelid doesn't added in the list
How do you know?
That’s why I used SQLite
Also you should use a database for this
i tried using it
oh
Yeah
Use SQLite
No
i use replit and that never happened to me
Aiosqlite
What
That’s what I am using
Python is python
except for this list
You said sqlite
Another replit user 😔
This is how lists behaves and dicts
cuz its free and i don't have a sugar daddy
Yeah, that’s what the db file says
Also that list's contents you will never see
VS Code is free
Because all of those contents disappear when the command finishes
Why do you want your bot to be 24/7 if you aren't ready to spend some money?
Why is it 24/7 in the first place
Nothing in this world is free
If you aren't making money off it
i just wanted to have a custom bot in my server
Which could be free
It doesn't have to be 24/7
Yeah
24/7 costs money
If you aren't ready to spend then don't make it 24/7
why not
Yea
Bro you didn't see
@supple thorn
!d discord.ext.commands.Bot.strip_after_prefix
Whether to strip whitespace characters after encountering the command prefix. This allows for ! hello and !hello to both work if the command_prefix is set to !. Defaults to False.
New in version 1.7.
What did you do
sign up for the Github education pack and make use of the azure credits :)
Text mode?
Just send text
idk how
!d discord.ext.commands.Context.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
@supple thorn
What
@bot.command()
async def help(ctx, category=None):
await ctx.send('```ini
BOT-HELP-CMD
[ .help ] Get help with a command
[ .admin ] Administration
[ .image ] Image commands
[ .fun ] Funny commands
[ .tools ] General tools```') it work like this?
but everytime i run it it doesn't work
what is this?
""" """
It's just
"""
Multi
Line
String
"""
What do you meab it doesn't work?
wait let me try it
@bot.command()
async def help(ctx, category=None):
await ctx.send("""```ini
BOT-HELP-CMD
[ .help ] Get help with a command
[ .admin ] Administration
[ .image ] Image commands
[ .fun ] Funny commands
[ .tools ] General tools```""") it work like this?
like this?
where to put """
Yes like that
okay let me try to run it
OMG THANK YOU SO MUCH
i have been 3 days trying to do it but not working
You're welcome
!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.
i did rpm craft pog sword
and i didnt get any output
no error also
line 135 is process about crafting pog sword
i get an error with this line, it says i need to clarify 'self' but i dont rlly know what it means, couldnt fild anything online so i figured i'd ask here
im typing before that and i was trying diff things
anyway, whats with the 'self' thing?
it refers to the object
refers to "class" thing, i believe you're using Cogs
but what do i put in self
..
for self, put self
Class thing
@slate swan the first agument that you've passed in init function is 'self'
Self refers to the instance of the class
?
that's what we do most of the time.. so..i hope u got my point ")
Happy Easter everyone💜
u too
💜
btw help rpm is the prefix
today's easter? :'/ i didn't even know :'/
ye
message.guild
Why are you using a default discord.Guild
what country
Use your message object to get the guild attribute
eh @slate swan .. despite of getting help with it.. i suggest u to learn about how to make commands
like.. we don't use message event like that
🇲🇾
im new to discord.py so im trying my best, but hey if it works it works, but its cleared up now thanks, btw i will learn further no worries
Heloo 🇲🇾 :>
👍
but make sure to learn python first
like at least until classes(min req LOL)
yeah tha'ts all good,
just saying, we don't make commands using on_message event
+1
What flag is that
@bot.command(name='hunt')
@commands.cooldown(1, 60, commands.BucketType.user)
async def hunt(ctx):
stats = Stats(ctx)
num1 = random.randint(0, 100)
num2 = random.randint(0, 100)
loot = 'nothing'
if stats.area == 1:
mobxp = 5
if num1 <= 50:
mobselected = 'pig'
mobdef = 1
mobatk = 0
i was thinking to wrap the discord api should i?
malaysia
Damn that was my guess
Surpass rin
Ayo someone stole my name
hard
damn that was my guess also
bro
?
@slate swan
Imposter
thats how i create command
😂
💀 ik, but okay, :")
at least delete the space between the words
...
😭 omgg i'm sorry
its the amongus song
oooo
du du du du du du du
😳
now better
idk how to spell solphage whatever
we can't hear u sing or spell anyways.. so nobody gonna know
never gonna let u down
LOL u can hear it
me too 😂
lets get back to business
before mod come and tells us to go to offtopic
Thread of life
Threat*
wow
lmao
ahem
the new advance thread!
:>
when we get the thread we have to say thank you to mina for sure
d.js users do exactly that 
🤨
😐
no ig 💀
here is d.py
it's alr.. but still? do they really? wtf
Yes
😐 oh
I experienced it myself
class Bot(Client):
async def on_message(self, message):
await self.process_commands(message)
``` a dummy representation of how commands.Bot class works with commands \:)
lol
it for sure uses on_message events
isnt commands the same as on_message they just call get_context and get_prefix i think im not sure how the internal works with detecting commands
yeah since d.js has no commands extension/plugin
🤔 ooo
yessir
🤔 i see
ily💜
tbh i never looked into the lib.. i just always referred docs lmao
i dont even read docs
ily too!💜
u pro :'/

https://paste.pythondiscord.com/ehutopiliy
i did rpm craft pog sword
and i didnt get any output
no error also
line 135 is process about crafting pog sword
:D
why is all my friends here
😩 ilym
hello frienddd
why are*
https://github.com/Rapptz/discord.py/blob/5456c0cae944f5e0dffb5de19cf18175e0d73011/discord/ext/commands/bot.py#L1369 is the trigger part of a command, you can check how that works with the get_context and process_commands methods in the file
discord/ext/commands/bot.py line 1369
async def on_message(self, message: Message, /) -> None:```
Sorry Kayle.*
LMAO
help me
;-;
i wiill marry u if u fix this bug
LMFAOOO
jkjk
i was about to open the link but now i step back
😂
you better 😡
LOL jk
may i know what that is actually supposed to do
do you have an on_message event?
do you have an on_command_error event?
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.send(f'''
Dont spam :/
Try again in another **{round(error.retry_after, 2)} seconds**
''')
else:
raise error
and any on_message, since that may block your commands from running
oki dont hide yourself
@bot.event
async def on_ready():
activity = discord.Game(name="RPMinecraft", type=3)
await bot.change_presence(status=discord.Status.online, activity=activity)
print('We have logged in as {0.user}'.format(bot))
bot.remove_command('help')
no more althought this is not on_message
😔
only 1
my_emote is a class right?
yye
i guess you should use f-string it's way more better
ill assume that the command works when you supply a single word arg or the number
right?
change the parser to cosume all the words in the command invocation ```py
async def craft(ctx, *, arg: str):
er
yes
do this
okok
thankss
idk how but its working LMAO
lemme explain
basically the code you had parsed only 1st argument so suppose you used the command as !craft pog sword, the arg variable is just pog sword is ignored, adding the * makes the command parse all the words which appear after the command invocation
if you are able to manage typing these many words and sending them, sure
no *,arg = !do my job output = my
yea
okok
.topic
Suggest more topics here!
Umm
idk mate i am out of ideas
Hmm
.ideas
Same
I’m making a leveling system, ig
i've made things that are unique and noone ever tried making them before
like a fivem server status bot
a game controller lol
through bot
Yea I am not that advanced
it isn't that hard
To make unique things, no
tbh, i find databases & leveling things quite confusing & hard
yeah, coming up with ideas is really hard
.topic
Suggest more topics here!
Yeaaaaaa
I have no idea :/
i think there are all features in the library now
back in 2021 they left dpy to rot like sh*t 💀
modals or dropdowns too lazy to learn them
i never tried any other lib for bot developing
Modals are so useful
I need to learn disnake
btw, do you guys know, how i can use the await timeout func cuz i can't seem to understand it
👀
I do not know that lib
Like timing out a member?
Yup
Nor do I know pycord
What lib are you using?
pycord is horrible i hate it
is it like await timeout(time in seconds,membername,reason)?
I like nextcord the best ngl
No
What lib are you using
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.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member.edit "discord.Member.edit").
that delay
Ikr
@slate swan i did look into the docs for it, but i was unable to understand it
When you answer my question
dpy
its just a method of the Member class?
you just use the method on a class instance of the Member class
so the await timeout(until) do we need to enter like uhh date in it or something
no
could you give me a short example?
await member_instance.timeout(float, reason="no reason")
You know how a string object has a lower() method right?
we enter a value in float right?, like seconds
That wouldn't work probably, it says until should be either a datetime or a timedelta obj
i haven't opened my ide for ages
as far as i remember there should be a timedelta obj there
but the problem is i can't understand what it is
From the docs (master)
wait nvm
yeah, i get it now
datetime.datetime is a date
and datetime.timedelta is a duration
e.g. when you subtract two datetime.datetime you get a timedelta
timee = datetime.timedelta(seconds=time)
await member.send(f'You have been timed out for {reason}')
await timeout(timee, member, reason)``` something like this? time & reason are args
@winged bone
😶
really?
Close, timeout is a member method, so you have to do member.timeout(...)
await timeout(*, duration=..., until=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Times out the member from the guild; until then, the member will not be able to interact with the guild.
Exactly one of `duration` or `until` must be provided. To remove a timeout, set one of the parameters to `None`.
You must have the [`Permissions.moderate_members`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.moderate_members "disnake.Permissions.moderate_members") permission to do this.
New in version 2.3.
this does take a float tho
👎
yeah but they use discord.py not disnake
not my point
like this, await member.timeout(time=arg,reason=arg2)
Do you mean the docs?
without time=
good thing i dont use master
What bothers you? Also, the 1.7 versions don't have built-in slash commands
what are you talking about?
Have you seen that: #discord-bots message
whos talking about slash commands💀
You said you don't like the master branch somehow
They have only been around since 2.0
it can control my pc from cmd to deleting or uploading files or writing in them
ok i know that but whos talking about them like really💀

youre trying to prove a point that isnt even related to this conversation and that i already know of so im not sure what you want to prove
, just stop the argument man
and listen to
Suggest more topics here!
how do i do timestamps n shit?
tbh it would be easier if message_content was not an intent but a scope instead
if the guild owners want them they could have just invited it with that scope, just like its done for slash commands
!d discord.utils.format_dt
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
oh, that exists too
ok... buuuuuuuuttttt how do i work out the integer?
because im wanting to put something in the bots about me
time.time()
How to display the ping and the author's message at the same time?
I tried to do something like thispy @bot.command(pass_context=True) async def send(ctx, member: discord.Member = None, arg): user = bot.get_user(member) text = arg await user.send(text)
The idea is that when you write !send @Member my best text the message should go to PM @Member and the text of the message should be "my best text", but I could not do it
hmmth
I'm not trying to prove anything. Was just curios what you don't like about it
does it return any errors?
yes
you can pass a datetime.datetime object into discord.utils.format_dt
what error
(ctx, member: discord.Member = None, arg):
^^^
SyntaxError: non-default argument follows default argument
no
you can't do py def foo(x=None, arg): ... you have to do ```py
def foo(x=None, arg=None):
...
okay thx
Command raised an exception: AttributeError: 'NoneType' object has no attribute 'send'
i send !send @swift imp message by me
Hi, do you know how I can add a event listener to my commands.Bot subclass?
I have something like this:
class Bot(commands.Bot):
@commands.Bot.listen("on_ready")
async def on_ready1():
assert self.user is not None
print(f"Logged in as {self.user} (id: {self.user.id})")```but that obviously does't work, because Bot.listen is an instance method which takes self and name
You can leave out the decorator
And change on_ready1 to on_ready
That way you override the default listener
hm yeah.
But if you want to add a listener as opposed to a event you’ll have to use self.add_listener() in your constructor
add_listener(func, /, name=...)```
The non decorator alternative to [`listen()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.listen "discord.ext.commands.Bot.listen").
Changed in version 2.0: `func` parameter is now positional-only.
like this? self.add_listener(self.on_ready1, name="on_ready")
thx
I was a bit confused, because when using Cogs, you can do this:
class MyCog(commands.Cog):
@commands.Cog.listener()
async def on_ready(self):
...```
that only happens with @bot.event - @listener() always appends the method to a list of callbacks, rather than replacing existing ones like @event does :P
not that there is a default listener for on_ready anyway iirc, but yeah
hi guys is it possible for my discord bot to take a screenshot of website and send it as a message in a channel?
As the name suggests that a Cog listener
Hello, So i wanted to connect paypal with my discord bot, something like donate bot, where you pay via paypal and you get privileges like roles or etc
I have created an app in paypal development account but all the tutorials i see online are django related and i am not sure how i should apply that to a discord bot, like in commands. I would appreciate any tips or leads, Thanks a lot
I personally use timestamps with the datetime API:
import datetime
Just use it in your command like this:
@bot.command()
async def test(ctx):
x = datetime.datetime.utcnow().timestamp()
await ctx.reply(f"{round(x)}")
And there you go with the timestamp. To format it, you need to use it like this:
await ctx.reply(f"<t:{round(x)}>")
You can also use this:
await ctx.reply(f"<t:{round(x)}:R>")
@swift imp hi, can you give invite to your server and give me owner (co owner)?
don't give random people owner
check if the user donated/paid using paypals API (https://developer.paypal.com/docs/api/payments/v1/)
Why, and what?
bro
hmm?
I am not random peop
friend?
@MZshnik hi, can you give invite to your server and give me owner (co owner)?
I just not random peop
you mean the module?
seems sus to me
My bad, yeah the module
im doing a discord bot that is requesting html and sending it but getting trouble installing lxml
pip3 install lmxl not working
not sure if i can ask this here an tecnically not question about discord bot
Maybe this helps
cool thank you ill try this
pip is not recognized?
i was getting that yes but
it just worked randomly haha
pip3 install lxml the first one i tried
just worked , i dont get it
mh
try python - m pip install
i appreciate it, but that was for the other person
oh
probably because you got multiple versions of python
ig he didnt add it in PATH
Yeah
How do i set if statement if user exists in db reply this ?
query your database and check
Is there any documention which may help for it
Its simple SQL bruv (as long as u using an SQL DB)
i feel ur using replit
Lol i hate it
Same but free is free
Also I can Dos on it
there are better, free options
and thats not even a host, a webserver is required to keep it running 24/7
Which?
Hekoru? Or something?
railway.app is a good choice, given that you would need a git repository ( either public or private )
K
another thing, the file system is ephemeral ( which is same for replit too)
K
I'm on it now
Threads for #discord-bots? 🧵
A temporary thread for the meta-discussion of topical threads specifically for discord-bots.
Discord Bot Hosting
For the discussion of deploying your bot and taking the next steps to make your bot available 24/7.
Discord API & Gateway
For the discussion of Discord API endpoints and Gateway without using an existing wrapper.
What? this should work...
could you show how you're defining the member?
Threads for subtopics within discord-bots
#965291480992321536 how do I reliably make my bot performant and available 24/7?
#965291516031549500 how do I work directly with Discord's API without a wrapper/library?
#965291445999239258 (temporary) I have a suggestion for a Discord bot subtopic!
It's happening
wait what....?
:0
could you show the whole traceback, like the above part which you sent?
what do you set the value of member if its None
nvm sarthak god here
oh no ash
yes it is
try removing the str() even though maybe it wont, but give it a try
^^^
I already set the value
set the value to?
Hi guys! I need help with my discord bot code. I try to make it activated 24/7 but it gives me weird errors, I use UpTimeRobot. I will copy paste the code here so if someone knows how to fix it, I will be so glad! ( I use Replit for it )
#Libaries Importation
import discord
from discord.ext import commands
import os
from keep_alive import keep_alive
#Client
bot = commands.Bot(command_prefix="!")
@bot.event
async def on_ready():
print(f'{bot.user.name} has connected to discord!')
@bot.event
async def on_member_join(member):
await member.create_dm()
await member.dm_channel.send(f'Welcome {member.name} to Magic-Tent server!\n Make sure to read the rules and verify.')
@bot.event
async def on_message(message):
if message.author == bot.user:
return
#Running the client
token = os.environ.get('Token')
keep_alive()
bot.run(TOKEN)
keep_alive.py
from flask import Flask
from threading import Thread
app = Flask('')
@app.route('/')
def home():
return "Hello. I am alive!"
def run():
app.run(host='0.0.0.0',port=8080)
def keep_alive():
t = Thread(target=run)
t.start()
read the #965291480992321536 channel (not a channel but a channel)
uptimerobot banned replit and this question belongs to the thread ashley mentioned
So how should I make the bot online for 24/7
I didn't find much information in google or youtuble tutorials...
Finally
ic new threads
weird since, avatar returns an Asset not an str, how are you running the command? (like mentioning a member or not)
I am just running it for me
so just
!level
Jonathan, how are you using VSCode for Bot coding?
I tried to use but it was super weird...
I downloaded it on my PC
You added discord to your Pip3?
You gotta install the Python extension
try typehinting ctx with commands.Context
?
How do I do it then
What is that gonna fix tho. dpy never converts the first arg (ctx)
Maybe I use nextcord instead
oh wait, yeah, forgot about that
Oh. Okay
I think I have it already
Install python -> Install Visual Studio/Code -> Install the Python extension within VSC -> Install discord.py with pip (pip install discord.py)
Yeah I did all of these.
Wait, @slate swan do u know how to see the active threads in the callstack? I have been using the threading module lately but it doesn't show the active threads
so i want my view to continue running
@commands.Cog.listener()
async def on_ready(self):
view=View(timeout=None)
view.add_item(select)
view.add_item(select2)
self.bot.add_view(view)
is that related to discord bots
but instead of class classname(discord.UI.view) i have class classname(command.Cogs)
yes, thats why you dont
threading.enumerate() ?
I cannot see those in the VSC UI
any answers?
no idea tbh
use a persistent view
I fixed it all 😄
So how do I make my bot activated 24/7 in VSCode?
You do not
If UpTimeRobot doesn't work and Replit..
It is a code editor
DEATH
So how Dyno, ModMail and these bots are activated at all the time?
They have a host
signs that i'm dumb
I just have a card that will not round
How do I set it up in VSCode then?
pfftt
it's in no way related to VSCode
A VPS
So in-case I want to make my bot active 24/7, which code editor or place should I use?
This has nothing to do with a code editor mate
Aw man :(
you "have" to "buy" a server from an organization, in order to keep your bot "online" 24/7
Yeah
sad
YES
Why caps lol
Because repl trash
👍
Thanks for the help and patience guys, I appreciate it.
😄
I have a command to just send any message to the participant in the bos, but when I try to do the same thing, an error is issued here
send the message before you kick, because the bot can only dm userd who are in the same guild as your bot's
@slate swan thank you ❤️
!d discord.Interaction.user
The user or member that sent the interaction.
Some wrappers have it as author, and some have it as user so I was a bit confused
But this would be it for discord.py
!d discord.Interaction.channel
The channel the interaction was sent from.
Note that due to a Discord limitation, DM channels are not resolved since there is no data to complete them. These are PartialMessageable instead.
how can i turn on my bot im new to this :,,v
Where do you have your bots code?
python3 <filename>.py
in my notebook, how do i run it now?
your terminal as robin told, or if you use some ide/code editors, there are extensions for that 👌
Running my bot with punch cards
Good idea
word is a good editor
and the event for greeting and saying goodbye to participants who have logged on to the server now works with restrictions ?
Yea, u need members intent
it's just that I seem to be doing everything right, and the bot does not react to the fact that anyone comes to the server
Code?
Hey guys how could I check if my string is already a key in a dict in a json file?
with open("users.json","r") as w:
users = json.load(w)
if user.id in str(users.keys()):
str(user.id) in users.keys()
fuck me
thx
Not a big deal, but you don't need the keys() call at the end, you can just do ```py
str(user.id) in users
That's very vague, what exactly isn't working, in exactly what way is it not working, and what steps have you taken to fix it so far?
You still haven't actually told us anything
Could you show your project directory layout?
All we see is a line under the word config
Why do you need config?
try from .config import *
You need to provide a bot token to run() so it can login to Discord, if you're using getenv() you could be returned None if you're trying to get an env var that isn't set, so I'd recommend using os.env["TOKEN_OR_SOMETHING"] so you either get a valid token or an error that makes sense
ye I hit enter too soon
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
hi can u help me for this ? Traceback (most recent call last):
File "C:\Users\skand\PycharmProjects\pythonProject1\main.py", line 26, in <module>
** @bot.command()**
AttributeError: module 'discord.ext.commands.bot' has no attribute 'command'
commands.Bot
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
Click the link
what is the easiest way to make a submit system where people can submit a text?
There's a little example in the docs on how to create your own modal: https://discordpy.readthedocs.io/en/master/interactions/api.html?highlight=modal#discord.ui.Modal
though you will only be able to send a modal to a user after an interaction like a slash command, button click, ...
fine I got an idea. The simplest way is to send a message to me from the bot
hey how would i select a different part of an argument
so say my argument is *args and i have 2 arguments ('1366', '0') how would i only select the second argument that being zero if i want it to send a message with that second argument and not the first or both
so if run !command 1366 0 it will send two messages being the first number and then the second number
@pliant gulch :white_check_mark: Your eval job has completed with return code 0.
bar
ohhh ok
ok so i may be trying to control my computer from a discord bot just for the fun of it and how would i get that to work in pyautogui.click
when i try and do it for positions it gives me errors
@bot.command()
async def clickat(ctx, *args):
argz = args
await ctx.send(args)
pyautogui.click(x=((argz)[1]), y=((argz)[2]), clicks=1, interval=1, button='left')
this being my code for that
just calling from args didnt work so idk
is there an error
it gives me this discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: tuple index out of range
not the full error if you need the entire error i can give
Traceback (most recent call last):
File "C:\Users\marti\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\marti\Documents\Discord bots\Why\bot.py", line 124, in clickat
pyautogui.click(x=((argz)[1]), y=((argz)[2]), clicks=1, interval=1, button='left')
IndexError: tuple index out of range
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\marti\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\marti\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\marti\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: tuple index out of range
Ignoring exception in command clickat:
Traceback (most recent call last):
File "C:\Users\marti\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\marti\Documents\Discord bots\Why\bot.py", line 124, in clickat
pyautogui.click(x=((argz)[1]), y=((argz)[2]), clicks=1, interval=1, button='left')
IndexError: tuple index out of range
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\marti\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\marti\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\marti\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: tuple index out of range
Your trying to index an element which doesn exist, KEEP IN MIND, INDEXES START AT 0
If you wanted to access the first element, use [0], the second, [1], and so on
ohhh
ty
that makes sense
keep in mind i have what is commonly called the big stupid
Anyone got any discord bot ideas
that solves that error but its giving me this now Ignoring exception in command clickat:
Traceback (most recent call last):
File "C:\Users\marti\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\marti\Documents\Discord bots\Why\bot.py", line 123, in clickat
pyautogui.click(x=((args)[0]), y=((args)[1]), clicks=1, interval=1, button='left')
File "C:\Users\marti\AppData\Local\Programs\Python\Python310\lib\site-packages\pyautogui_init_.py", line 598, in wrapper
returnVal = wrappedFunction(*args, **kwargs)
File "C:\Users\marti\AppData\Local\Programs\Python\Python310\lib\site-packages\pyautogui_init_.py", line 980, in click
x, y = normalizeXYArgs(x, y)
File "C:\Users\marti\AppData\Local\Programs\Python\Python310\lib\site-packages\pyautogui_init.py", line 661, in normalizeXYArgs
location = locateOnScreen(firstArg)
File "C:\Users\marti\AppData\Local\Programs\Python\Python310\lib\site-packages\pyautogui_init.py", line 175, in wrapper
return wrappedFunction(*args, **kwargs)
File "C:\Users\marti\AppData\Local\Programs\Python\Python310\lib\site-packages\pyautogui_init_.py", line 213, in locateOnScreen
return pyscreeze.locateOnScreen(*args, **kwargs)
File "C:\Users\marti\AppData\Local\Programs\Python\Python310\lib\site-packages\pyscreeze_init_.py", line 373, in locateOnScreen
retVal = locate(image, screenshotIm, **kwargs)
File "C:\Users\marti\AppData\Local\Programs\Python\Python310\lib\site-packages\pyscreeze_init_.py", line 353, in locate
points = tuple(locateAll(needleImage, haystackImage, **kwargs))
File "C:\Users\marti\AppData\Local\Programs\Python\Python310\lib\site-packages\pyscreeze_init_.py", line 262, in _locateAll_python
needleFileObj = open(needleImage, 'rb')
FileNotFoundError: [Errno 2] No such file or directory: '1366'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\marti\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\marti\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\marti\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: FileNotFoundError: [Errno 2] No such file or directory: '1366'
There are some good ones :P
The error pretty much tells you what is happening, 1366 doesn't exist
You need to make sure you have a real file name 1366
im tryna have 1366 be where to move click on screen
1366 being the far right edge of my screen
I'm trying to find a way to host my discord bot, I have old pc home but honestly letting them run 24/7 sounds very bad for my personnal electricity consumption, and it means I would have to instal python all over again (doesn't sound that bad tho), and after talking a bit with a discord bot developper (a very very good one), he told me about a service called soyoustart, and that I need linux knowledge that I clearly don't have. I don't have Linux, just windows, and maybe he wasn't talking about that one lol. Anyway I see a lot of video online about hosting for free etc, but it seems stupid and the pinned message about that also explains I shouldn't use free services, It's just that I don't understand how to put my bot on a VPS or something like that, would there be any good documentions about the topic by any chance ?
how to delete all channels in discord.py?
I have never heard of that company/host. Personally I would recommend you go with some of the more well known ones (aws, google cloud, microsoft azure, oracle cloud, etc)
But the best way would be to dockerize your bot, and deploy it to your VPS
You'd basically SSH into the machine your VPS gives you, which is like controlling a remove computer somewhere else, as if you were sitting in front of it
so???
From there, depending on if you have your bot dockerized, you would install python, your app's dependencies, etc. With docker you won't have to do this
Sounds suspicious. For what reason?
i want to restart my server
So delete it and make a new one
I made enable/disable commands for a leveling system, but when I disable it it will not work anymore unless I retype all the code? Why is that? (There is no traceback for this)
@bot.command(aliases=['e', 'en'])
@commands.has_permissions(manage_guild=True)
async def enable(ctx):
async with bot.db.cursor() as cursor:
await cursor.execute("SELECT levelsys FROM levelSettings WHERE guild = ?", (ctx.guild.id,))
levelsys = await cursor.fetchone()
if levelsys:
if levelsys[0]:
return await ctx.send("The leveling system is already enabled.")
await cursor.execute("UPDATE levelSettings SET levelsys = ? WHERE guild = ?", (True, ctx.guild.id,))
else:
await cursor.execute("INSERT INTO levelSettings VALUES (?, ?, ?, ?)", (True, 0, 0, ctx.guild.id,))
await ctx.send("Successfully enabled the leveling system!")
await bot.db.commit()
@bot.command(aliases=['d', 'dis'])
@commands.has_permissions(manage_guild=True)
async def disable(ctx):
async with bot.db.cursor() as cursor:
await cursor.execute("SELECT levelsys FROM levelSettings WHERE guild = ?", (ctx.guild.id,))
levelsys = await cursor.fetchone()
if levelsys:
if not levelsys[0]:
return await ctx.send("The leveling system is already disabled.")
await cursor.execute("UPDATE levelSettings SET levelsys = ? WHERE guild = ?", (False, ctx.guild.id,))
else:
await cursor.execute("INSERT INTO levelSettings VALUES (?, ?, ?, ?)", (False, 0, 0, ctx.guild.id,))
await ctx.send("Successfully disabled the leveling system. :/")
await bot.db.commit()
Because automating this could easily be used maliciously
the feature you're asking for is too similar to that of a nuke bot
so no, please don't ask for help on this
Right, so I'm reluctant to advise you on how to do so
Hi, I've got a question : I've got Py-cord and discord.py both installed (via pip), which one will be imported when I type import python ?
if i make a nuke bot discord will ban me because that is breaking ToS
Right
@bot.command()
async def delchannels(ctx):
for c in ctx.guild.channels: # iterating through each guild channel
await c.delete()
``` something like that
whichever one you choose
thanks
wait is that from stack overflow?
how do I chose tho ?
I would advise we don't help them as it seems to be bordering on rule 5 and could be used maliciously
.
It says import could not be resolved for pycord. When I go to pycord github, then import "discord" : @frozen patio
Oh sorry didn't know
I do not use those so idk
pycord hm
done
@frozen patioapparently pycord is a fork of discord.py. So they're imported using the same command (import discord), but how does python know which one I want ?
uninstall discord.py
I can use nextcord & python seperately with no questions asked
and don't ping people for help, there are tons of other people that can help around here
Sorry for pinging
Do you have jishaku?
👍
I'm sorry imma sound very stupid but it's like reading mandarin to me lmao
is that the only way to do it ? how can I know for a module, which one will be imported by default if they're imported the same way ?
No,
I do not mind the pings
It"s a new world for me, I already achieved a lot by making a working bot haha, and well You'd basically SSH into the machine your VPS gives you 😅
Do you have an on_command_error event?
Nope.
show a screenshot of how your invoking the command
I am not inkoving it
you are
Can you add debug print statements into the code to see where it stops
How do you want me to do that?
by adding it.. inside your enable command
I do not use print debug commands so I do not know how to add those
print statements
print()
What do you want me to print
anything
Oh ok
I did that
That's usually what I do
No traceback
I usually print problematic variables to see what they are
did you run the command?
My apologies, SSH stands for "secure shell", it lets you access the shell of a different computer remotely
From there, you can run your bot file like you might on your regular computer
That is,
python3 <filename>.py
hoo
that'll run the file on the vps?
Sure you can: mkdir
Yes, no traceback
Yes it would
that sounds so out of my range of skills omg
A little bit of linux knowledge would be helpful
what did it print
ye I know nothing haha
Nah. SSH is a very important tool in the server world
!pypi discordbotweb
I use it to SSH into my AWS EC2 instance where I host my bot
It only printed my on_ready event
As someone currently making a dashboard for my bot I find this very offensive 😂
Nothing else
well the thing is, I learn nothing at university, 3rd year of pure physics and all we did during the first semester was numpy and fourier transform
svelte my beloved
show your console
😂
I made it long ago
Pretty simple
Well I don't suspect they'd be teaching you SSH and server management unless you specifically go in that field
Im tryna also make people websites for money
and well discord bot was a very cool experience
show a screenshot of you where you ran the command
If you want to, you can buy yourself a raspberry pi and host it yourself
Discord bots are coool
Electricity and internet bills are basically nonexistent
sounds crafty
What are you using?
Cheaper than hosting
Ho that's nice
Nah, I do that as well
no way!
Flask for server and html css js for design
Internet bill isn't an issue If i'm on wifi lol
Oh cool, I'm trying to sharpen my skills with React.js :D
Nice
sounds like a big improvement even if I have no idea what that is
I could also make websites with flutter
If I were needed to compute a lot something like pillow but with a web request that needs to return a lot of data and filtering using regex and sync bs4. Is it best to make an API for that and just have it run trough aiohttp with my bot?
Amazon web services. One of the largest PaaS providers on the internet
hi can u help me for this I installed pip install discord-py-slash-command and py -3 -m pip install -U discord-py-slash-command
flutter is WordPress but for apps😂
Discord.py has built in slash commands, no need for bad external libraries
Lmaoo
I need to make a extra few bucks for my friend
ok
thx
No prob
@sick birch thoughts?