#discord-bots
1 messages · Page 761 of 1
!d discord.Guild.create_text_channel
await create_text_channel(name, *, reason=None, category=None, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel "discord.TextChannel") for the guild.
Note that you need the [`manage_channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to create the channel.
The `overwrites` parameter can be used to create a ‘secret’ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite") as the value.
Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
!d discord.Embed
class discord.Embed(*, colour=Embed.Empty, color=Embed.Empty, title=Embed.Empty, type='rich', url=Embed.Empty, description=Embed.Empty, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty").
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
The documentation offers all the necessary resources, if you are stuck on the actual execution or construction, ask for help.
yes
Fyi you can remove the string slice and replace it with the .display_name / .name attribute of a discord.Member object
i dont know how to put it into the create_text_channel code
You just need to supply the kwargs you want, you can do this in one line
e.g. name = 'general-chat'
discord.py was not intended to be used by beginners, if you find the concept of kwargs or async code confusing, please learn that first
how can i put mobile phone status on the boot
It's not advised to do so, it's a bug in the Discord API and will be patched. Bots shouldn't have mobile statuses
Ok
@bot.command()
@commands.has_permissions(administrator=True)
async def unban(ctx):
server=ctx.guild
ban_list = await bot.get_bans(server)
await ctx.send('Desbaneando a todos los miembros.')
for member in ban_list:
await ctx.guild.unban(member)``` I'm trying to unban 1700 people. This is the traceback: ```Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(args, **kwargs)
File "main.py", line 40, in unban
ban_list = await bot.get_bans(server)
AttributeError: 'Bot' object has no attribute 'get_bans'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/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: AttributeError: 'Bot' object has no attribute 'get_bans'```
get_bans isn't a thing
how i can do it?
!d discord.Guild.bans
await bans()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves all the users that are banned from the guild as a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`BanEntry`](https://discordpy.readthedocs.io/en/master/api.html#discord.BanEntry "discord.BanEntry").
You must have the [`ban_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to get this information.
You don't need to iterate through the list/ you don't even need to get all the bans from the guild.
!d disnake.Guild.unban
await unban(user, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Unbans a user from the guild.
The user must meet the [`abc.Snowflake`](https://docs.disnake.dev/en/latest/api.html#disnake.abc.Snowflake "disnake.abc.Snowflake") abc.
You must have the [`ban_members`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.ban_members "disnake.Permissions.ban_members") permission to do this.
Just use that
so like server.bans()
.
You will need to iterate through the entire guilds' bans to unban more than one person
Fyi sending 1700 consecutive API requests to Discord to unban that many people will have your bot ratelimited
And IP blocked temporarily
Helloo, so i think this is more of a replit problem than actual bug int he code. so i put my discord bot code into replit and then ran it, and instead of running it gave me this error: ```
Because no versions of discord match >1.7.3,<2.0.0
and discord (1.7.3) depends on discord.py (>=1.7.3), discord (>=1.7.3,<2.0.0) requires discord.py (>=1.7.3).
Because discord.py (1.7.3) depends on aiohttp (>=3.6.0,<3.8.0)
and no versions of discord.py match >1.7.3, discord.py (>=1.7.3) requires aiohttp (>=3.6.0,<3.8.0).
Thus, discord (>=1.7.3,<2.0.0) requires aiohttp (>=3.6.0,<3.8.0).
So, because repl-python3-challengebot depends on both aiohttp (^3.8.1) and discord (^1.7.3), version solving failed.
at /opt/virtualenvs/python3/lib/python3.8/site-packages/poetry/puzzle/solver.py:241 in _solve
237│ packages = result.packages
238│ except OverrideNeeded as e:
239│ return self.solve_in_compatibility_mode(e.overrides, use_latest=use_latest)
240│ except SolveFailure as e:
→ 241│ raise SolverProblemError(e)
242│
243│ results = dict(
244│ depth_first_search(
245│ PackageNode(self._package, packages), aggregate_package_nodes
exit status 1
Replit: Package operation failed.``` so basically aiohttp and that python version aren't really cooperating? Can someone pls tell me how to fix this? I'm very new to repl, so this may seem easy to some of you. pls ping when you respond
ive tried doing a different repl, but that seems to have no effect whatsoever
Long story short, don't use replit @jade sinew.
You should not use Repl.it to host your bot.
While this may seem like a nice and free service, it has a lot more caveats than you might think, such as:
- The machines are super underpowered.
-
- This means your bot will lag a lot as it gets bigger.
- You need to run a webserver alongside your bot to prevent it from being shut off.
-
- This isn't a trivial task, and eats more of the machines power.
- Repl.it uses an ephemeral file system.
-
- This means any file you saved via your bot will be overwritten when you next launch.
- They use a shared IP for everything running on the service.
This one is important - if someone is running a user bot on their service and gets banned, everyone on that IP will be banned. Including you.
Please avoid using repl.it to host your bot. It's not worth the trouble.
avatar.url
😬 i didnt know repl was that bad. but i cant find any other systems that will let me host my bot 24/7/365 for free. can you give me any advice?
Nothing in life is free
If you have any money, purchase a VPS, they're around $4 per month
No free hosts are as good as paid ones. And that they aren't even for discord bots to be hosted on.
i have $0 money and no credit card even if i did
Air 
GitHub student packs offer free DigitalOcean credits.
but im not a github student
Are you a student?
yes
Netcup has hosting starting at 2.80 eu
Apply for it
If you provide a school email, you'll get it really quickly
Oh, and AWS gives a free year I believe
i tried using heroku, but once i tried hosting multiple bots i lost my free dyno hours
Bruh
hmm these suggestions all sound great! thanks!
That's a poetry related error
If you're a student, take advantage of the GitHub student pack, it's wild
ill try them all out
GitHub pack also gives azure 100 bucks
That should fix the issue
yeah, but i dont know how to change it to like a stable version
Just don't use replit, it's the wrong way to start out programming
where do i put this
yikes ok
Use shell do it
ohh
-_-
poetry add aiohttp@3.7.4.post0
lol ty
Yeah you should not use replit I know but its actually not the issue with replit but poetry
ok
It's better suited for things like Flask and Django web apps. But at that point you may as well use a VPS
Better to learn web development that way imo
Nginx + gunicorn doesn't hurt anyone
You don't
You can't "hide" slash commands
you can change the permissions the to grey them out
Since slash commands are meant for users and not for devs to debug
Looks bad if they can still see it imo
I mean yeah, you can't do much anything more than that
slash commands permissions v2 is still developed by discord
I have a slash bot aswell that I'm coding rn
I combined both slash and prefix. Using the prefix for debugging, no help command no bot responses just for debugging.
Well, technically you can make slash commands not visible in other guilds besides the ones you want
@jade sinew did it work?
Pretty messy solution
If you would ever make them global
That's an ephemeral message
it worked! but now im going to try to host it with something else, because as y'all said, replit is bad
Ah okay
With disnake it's pretty easy to make
@bot.slash_command(name="test")
async def (inter: disnake.ApplicationCommandInteraction):
await inter.response.send_message("hello", ephemeral=True)
That's it
the ephemeral kwarg needs to set to True and you will be able to send ephemeral messages
Oh wait, you meant hidden slash commands this?
Oh I thought you were talking about hiding the slash command itself
Ah
would this channel fit for asking how to make my chatbot into a discord chatbot?
In the command, with the db.execute things, does it put me at this stage?
Fuck forgot the reply
^
@modest ploverif u like GUI (wich can simplifie the creating of database's for sqlite3) checkout DB Browser https://sqlitebrowser.org/
so i got this python chatbot thats completely unrelated to discord, is this where i should ask how to make it into a discord chatbot?
@rugged laurel start read about how to write a discordbot and u will understand how merge them both, https://docs.disnake.dev/
code: py @commands.command(aliases=["ub"]) @commands.has_permissions(ban_members=True) async def unban(self, ctx, member:discord.User, *, reason="none"): user = await self.bot.fetch_user(member.id) try: em1=discord.Embed(description=f"{member.mention}, you have been `unbanned` for **{reason}**", colour=0) await user.send(embed=em1) except: pass em2=discord.Embed(description=f"{member.mention} has been `unbanned` for **{reason}**", colour=discord.Colour.green()) await ctx.send(embed=em2) await ctx.guild.unban(user, reason=reason)error:
discord.ext.commands.errors.CommandNotFound: Command "unban" is not found```
Did you load the Cog?
COG?
You know what that is right?
!d discord.ext.commands.Cog
class discord.ext.commands.Cog(*args, **kwargs)```
The base class that all cogs must inherit from.
A cog is a collection of commands, listeners, and optional state to help group commands together. More information on them can be found on the [Cogs](https://discordpy.readthedocs.io/en/master/ext/commands/cogs.html#ext-commands-cogs) page.
When inheriting from this class, the options shown in [`CogMeta`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CogMeta "discord.ext.commands.CogMeta") are equally valid here.
what does this error mean?
discord.ext.commands.errors.MissingRequiredArgument: member is a required argument that is missing.```
You didn't pass member to that command
I don't recommend copying code
i dont recommend assuming :((
I felt pretty confident
ok but i didnt copy, i rushed the code today.
why .id
why not
ok, so who is user
user
not defined there
u rushed it or copy my shitty old exmaple? #discord-bots message
i would't copy it but more take some references from it
it was more likely i rushed it...
parameter's name is bad and alot in that code is bad
lmfao
but i had to type, cause u try tell others u rushed it 🙂
Imagine banning users instead of members
I can't use it, I'm on mobile
client.run(TOKEN)
with open('words.json') as f:
dit = json.load(f)
@client.event
async def on_message(message, word):
username = str(message.auther).split('#')[0]
user_message = str(message.content)
channel = str(message.channel.name)
print(f'{username}: {user_message} ({channel})')
if message.auther == client.user:
return
if message.channel.name == 'testing':
if word == 'add.pattern':
key = input('Enter the word: ').lower()
value = input('Enter A.I. response: ')
dit[key] = value
with open('words.json', 'w') as f:
json.dump(dit, f)
word = input('? ').lower()
elif word in dit:
print(dit[word])
word = input('? ').lower()
else:
word = input('? ').lower()
if word not in dit:
key = input('I dont think i understand, please repeat the word.: ').lower()
value = input('Enter A.I. response: ')
dit[key] = value
with open('words.json', 'w') as f:
json.dump(dit, f)
word = input('? ').lower()
can anyone help me fix the error im getting on line 31, 9
its something with "key" not working
i need to fix this so it works with the discord py library
what’s the error
I'm very confused on why this would ever work
^
First of all this code can never be reached.
Second of all this is very blocking.
@bot.command()
@commands.has_permissions(administrator=True)
async def unban(ctx):
server=ctx.guild
ban_list = await server.bans()
await ctx.send('Empezando a desbanear a todos los miembros.')
for ban_entry in ban_list:
member = ban_entry.user.id
await server.unban(member)
await ctx.send('He acabado de desbanear a todos los miembros.'
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 45, in unban
await server.unban(member)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/guild.py", line 2052, in unban
await self._state.http.unban(user.id, self.id, reason=reason)
AttributeError: 'int' object has no attribute 'id'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/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: AttributeError: 'int' object has no attribute 'id'```
why do i get this traceback?
it’s not server.unban
well im trying to rewrite a chatbot so it becomes a discord chatbot
i defined server
You set server to ctx.guild
ye
yeah
idk why i get that xd
tbh I would put that stuff in the params but it doesn’t matter
How do you invoke the command
PS C:\Users\esben\Desktop\Bob the Chatbot> & C:/Users/esben/AppData/Local/Programs/Python/Python36/python.exe "c:/Users/esben/Desktop/Bob the Chatbot/discord-bot.py"
Traceback (most recent call last):
File "c:/Users/esben/Desktop/Bob the Chatbot/discord-bot.py", line 8, in <module>
client = discord.client()
TypeError: 'module' object is not callable
PS C:\Users\esben\Desktop\Bob the Chatbot>
im getting this error, ima send script rl quick
how do you type it in discord
-unban
that’s it? you don’t specify a user?
no, its a unban all
Hey @rugged laurel! 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!
so i have the id of every member but the bot doesnt unban them
oop
That's no good lmao
and i get that traceback
from asyncio import events
import json
import discord
import random
TOKEN = ""
client = discord.client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
client.run(TOKEN)
with open('words.json') as f:
dit = json.load(f)
@client.event
async def on_message(message, word):
username = str(message.auther).split('#')[0]
user_message = str(message.content)
channel = str(message.channel.name)
print(f'{username}: {user_message} ({channel})')
if message.auther == client.user:
return
if message.channel.name == 'testing':
if user_message in dit:
await message.channel.send(dit[word])
word = user_message('? ').lower()
else:
word = user_message('? ').lower()
if word not in dit:
await message.channel.send(f'i dont think i understand')
so how do i fix error
PS C:\Users\esben\Desktop\Bob the Chatbot> & C:/Users/esben/AppData/Local/Programs/Python/Python36/python.exe "c:/Users/esben/Desktop/Bob the Chatbot/discord-bot.py"
Traceback (most recent call last):
File "c:/Users/esben/Desktop/Bob the Chatbot/discord-bot.py", line 8, in <module>
client = discord.client()
TypeError: 'module' object is not callable
PS C:\Users\esben\Desktop\Bob the Chatbot>
remove .id from ban_entry.user.id
Hello, I have a question i wrote this for out of the cog but i want it to work in a cog i have it this far but i get a name error py @commands.Cog.listener() async def on_ready(self): for guild in client.guilds: print(guild.name) print( f'{client.user} is connected to the following guild:\n' f'{guild.name}(id: {guild.id})\n' )
okk
can anyone pls help me with this error, i cant see what i made wrong
What's the full error?
it works, thank u! @slim ibex
It's discord.Client() not discord.client()
np
discord.Client(), CaPiTaLiSe
self.client.guilds
i feel insanely stupid😂
or whatever you have named your bot instance
yep
wait
its not working
the dit isnt working it aint getting from words.json
client.run(TOKEN)
with open('words.json') as f:
dit = json.load(f)
@client.event
async def on_message(message, word):
username = str(message.auther).split('#')[0]
user_message = str(message.content)
channel = str(message.channel.name)
print(f'{username}: {user_message} ({channel})')
if message.auther == client.user:
return
if message.channel.name == 'testing':
if word == 'add.pattern':
key = input('Enter the word: ').lower()
value = input('Enter A.I. response: ')
dit[key] = value
with open('words.json', 'w') as f:
json.dump(dit, f)
word = input('? ').lower()
elif word in dit:
print(dit[word])
word = input('? ').lower()
else:
word = input('? ').lower()
if word not in dit:
key = input('I dont think i understand, please repeat the word.: ').lower()
value = input('Enter A.I. response: ')
dit[key] = value
with open('words.json', 'w') as f:
json.dump(dit, f)
word = input('? ').lower()
this is original python terminal code
this is discord rewrote code
like it launched
but it doesnt repply to me
@rugged laurel I'm sorry but it's fair to say you skipped the basics of Python, i recommend learning that first then get back to it.
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
i have learned basic python. i just struggle with synax sometimes and then also new packages i find confusing
ok in both spots aswell?
Well i did already told you why it doesn't work but you reposted the code just now.
username = str(message.auther).split('#')[0]
if message.auther == client.user:
its author tho
@rugged laurel
wdym
And message.author.name lol
.auther not correctly spelled
oh
wherever you would normally use client just make it a thumb rule to add self before that. E.g
client.user
client.guilds```
cogs
```py
self.client.user
self.client.guilds```
lol
yes i fixed it my self thanks for telling me i missed the self part
right thank you
@cloud dawnhey its a hard word if non english speaking n maybe dyslexia 🙂
No worries
I'm non English and have a dyslexia certificate.
i just tend to swap around on "or" or "er"
same xD but no cert but for sure has it
its prob prefix problem
ik but if i get it to work i can super easily train it whenever i want to
can anyone tell me why my loop isnt working inside my cog?
class updates(commands.Cog):
def __init__(self, client):
self.client = client
self.index = 0
@tasks.loop(seconds=5.0)
async def printer(self):
print(self.index)
self.index += 1
def setup(client):
client.add_cog(updates(client))```
Did you start the loop?
how do you start the loop?
self.printer.start()
thanks
wait how do i make a bot that has a database of words and patterns, and then a command to create new ones?
and then the command should be like /ap:Hi:Hello
We can help you going trough it a bit, but we won't code it for you.
ik
https://vcokltfre.dev/ Use this to get started with discord.py
https://vcokltfre.dev/tips/storage/ Use this for database selection
how do i take the commands out of cog and put them in cog?
When I first start my bot, all the @tasks.loop run. Is there a way to immedietely add the delay. So if I have tasks setup to run every 1 hour, it will run 1 hour after the bot has started
Don't do anything..?
lol i mean i could
@daring olive Sorry for the ping :3
Thought you might be interested.
Wait what's this?
yup i saw
You DMed ModMail to ask a Discord API question???
i was a part of the discussion lol
Regarding the invite creates by bots.
Ah, joining random servers from bot.guilds?
rereading that code yesterday, i also noticed the docstring in the function was misleading right?
the docstring seemed to indicate that it would create and post an invite link in the topmost channel of the server
Ahhh okay.
How to make tasks.loop execute randomly between 1-3 hours?
randint.
yep
is SQLite good for bots? some say it's not good?
For smaller bots it's perfect :3
Do use the aiosqlite lib though
How many guilds?
like around 500?
That is still considered small
what's the range of "small bots"?
sqlite is for around 20/25k guilds
oh damn
this is basic python :/
I saw this and I was like why is everyone saying it's bad for bots..
https://www.sqlite.org/famous.html
thants not few tho
yeah
@dense swallowwhen u got ur sql up consider do daily backups or so too
to not lose data?
😂 k
or if u misstaken ly does something
hmm yeah
then u can also delete old backups that are too old
I was considering switching to mongo, but I really don't like the syntax and Postgres hosting costs a lot for good one
i nvr been intressted in mongo :S
same
its sqlite for local db, or prettymuch mysql for remote db
u can get cheap vps
I don't have any income
but u dont even have $5 month?
how can a student earn?
137$ each month for free
no just bein going to school
hmm
Hi i have my welcomer that was made out of cog but i am working on classing items so i was wondering how to convert to cog and want to make sure it is correct because i don't have a test function ```py
#Client Events
@commands.Cog.listener()
async def on_member_join(member):
if member.guild.id == 804864012184977438 : return
channels = member.guild.channels
for channel in channels:
if ('welcome' in channel.name) or ('joins' in channel.name): #or ('testing' in channel.name)
embed=discord.Embed(title=f"Welcome {member.name}", description=f"Thanks for joining {member.guild.name}!")
embed.set_thumbnail(url=member.avatar_url)
await channel.send(embed=embed)
@commands.Cog.listener()
async def on_member_remove(member):
if member.guild.id == 804864012184977438 : return
channels = member.guild.channels
for channel in channels:
if ('leave' in channel.name) or ('Goodbye' in channel.name): #or ('testing' in channel.name):
embed=discord.Embed(title=f"Goodbye, {member.name}", description=f"Bye {member.name} come again soon")
embed.set_thumbnail(url=member.avatar_url)
await channel.send(embed=embed)```
Hello, is there a way to get the first channel in a category and move it into another one ?
I know how to move a channel to another category but i don't know how to get the first channel of a category.
dunno and too lazy just ate, but grab the category
u want -> category.channels[0] something that way
nothing much should change(I think), but just pass self as a param and what I told you earlier
also you should update to dpy 2.0+ or a fork
How do i send a user a dm from d.py This is my code = @Bot.command()
async def DM(ctx):
user_id_list = [user_id]
for user_id_list in user_id_list:
user = await Bot.get_user_id(user_id)
await user.send('this is a test dm')
anyone know to how to add gif emojis to py i tried the old method but it didn't work
!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.
yea this is how u do it
wym
I mean... you can do
@bot.command()
async def dm(ctx, member: discord.Member):
await member.send(...)
but I think they wanted to DM everyone 🤷♂️
uh...what?
like for example if you wanted to add a gif emoji to your welcome command, how would i do that?
u need its ID and name
like !python
u get this with \:emoji-name:
and add this to yr code
you can add a \ before the emoji to get it's- fuck
!yert

flexing your nitro
gonna end in a day or two
oh
wait its ending today :DDD
enjoy it while it lasts
How difficult is it to create a website splash page like most high quality bots have? Is there a framework for building them?
A discord.py extension for inter-process communication.
Cool, thank you 🙂 I'd assume there is additional work to be done, say creating a react frontend or something to make it look more attractive as I know flask apps don't by default look very appealing
For that, u can look into jinja2
don't you just need a button and a redirect to the invite link? Or...
Or you can also look into svelte and Brython @ebon island
Lol its much more than that
o
No, I am looking for a dashboard framework for customizing settings and all via dashboard
I will look into them 🙂 What are the key differences in each?
Ah, well the most basic implementation for something like that would be: Suppose u have an option to change the logging channel, then u display the list of all the channels u got, after requesting them from the bot and show them on the website... When the user clicks one, u just edit the database
Brython is like JS, but u can use Python for frontend.
Svelte is an HTML subscript language to build a frontend which compiles to JS
Found a relevant YT video, appears by the code snippets seen in the video to be JS but it's definitely something to consider while I continue searching for a Python based implementation
Talking about svelte?
Its just an easier way to combine HTML and JS codes haha
Its a programming cum markup language in itself
And then there is sveltekit, a framework similiar to React implemented in Svelte to create backend and frontend, still in beta tho
So what u can do is, create a websocket connection with the bot, and just request for things through it... That is what discord-ext-ipc does
So i am using an ignoring fuction in my welcome and leave is there a way i can have a document like a .txt file with all the id's in it that it checks?
use a db
.txt files arent fit to store data
if you did read a text file would it just be one long string?
i think so im not sure
your params
whats wrong with them?
it thinks your time is a member
i honestly don't see an issue
not the way i coded it
it's in the pastebin
then your calling it wrong
You have to invoke it in the order of the params
^
i did though?
seems like you have something wrong
yeah
once again it's in the pastebin.
it's been broken like this for a few days
it's saved
any errors in terminal?
it thinks temp is the member
which doesn't make sense
your adding extra params
<prefix><ctx><another_argument><member_obj><duration>
it's a subcommand. it's more like <prefix><subcommand><member><duration>
Does the regular mute work
async def Ping(self, ctx):
await ctx.channel.send(f"**pong!** That took {int(self.bot.latency*1000)} ms!")```
worked fine out of cog
self.bot
show your cog
ok
import os
import discord
import time
import datetime
import asyncio
from discord.ext import commands
class CMS(commands.Cog):
def __init__(self,client):
self.client = client
#Ping command
@commands.command(name='Ping')
async def Ping(self, ctx):
await ctx.channel.send(f"**pong!** That took {int(self.bot.latency*1000)} ms!")
#Purge command
@commands.command(name='Purge')
@commands.has_permissions(manage_messages=True)
async def Purge(self, ctx, limit: int):
await ctx.message.delete()
await asyncio.sleep(1)
await ctx.channel.purge(limit=limit)
purge_embed = discord.Embed(title='Purge [%Purge]', description=f'Successfully Purged {limit} messages. \n Command executed by {ctx.author}.', color=discord.Colour.random())
purge_embed.set_footer(text=str(datetime.datetime.now()))
await ctx.channel.send(embed=purge_embed)
#Help Command
@commands.command(name='Help')
async def Help(self, ctx):
embed=discord.Embed(title='Help Page!', description=f"%Ping (To tell you if I am online or not) \n %Purge (To purge mass messages) \n %Invite (Opens the invite page to invite me!) \n %Help (To open this page to tell you what commands I have)", color=0x206694)
await ctx.channel.send(embed=embed)
def setup(client):
client.add_cog(CMS(client)) ```
Help command works trying purge work
self.client
were the heck i cant find it lol
what you looking for
ok
noice
now how do you add a false statement on a purge command as what i have above
i mean look
@steel slateu should try read some about python 🙂
what about it
or u gonna keep asking for simple things over n over
i got it
I know it is just i can't speak today
chill out
make all the questions you want :))
and i want to make sure it right
wdym by false statement?
you know like how carl bot says you don't have perms todo that but if you do have perms he does it like that
a an error handler
that is what i was thinking of because i get the error here but not in discord
@commandname.error
async def example_error(self, ctx, error: commands.CommandError):
if isinstance(error, commands.MissingPermissions):
await ctx.send(f"{ctx.author.mention}You do not have permissions to do this command.")
something like this
this just checks if the error is the given instance
bingo thank you
yw
also how do i make it so if you don't put a number it just doesn't do anything?
it tells you to add a number
check the type
if type(limit) == str:
# do something
if you have a command error it will just handle it as a bad argument
@client.command()
async def testt(ctx):
await ctx.send("hello", components = [
[Button(label="hi", style="3", emoji= "🛴", custom_id="button1"), Button(label="hi2", style="4", emoji= "🛴", custom_id="button2")]
])
interaction= await client.wait_for("button_click", check= lambda i: i.custom_id == "button1")
await interaction.send(content = "test done")
Interaction failed?
i ment like the person does %purge it won't do anything i want it to comback and say this is how you need to do it
well then use a return statement
if type(limit) == str:
return await ctx.send("you must do the command as so....")
now it doesn't go at all with error statement
@commands.command(name='Purge')
@commands.has_permissions(manage_messages=True)
async def Purge(self, ctx, limit: int):
await ctx.message.delete()
await asyncio.sleep(1)
await ctx.channel.purge(limit=limit)
purge_embed = discord.Embed(title='Purge [%Purge]', description=f'Successfully Purged {limit} messages. \n Command executed by {ctx.author}.', color=discord.Colour.random())
purge_embed.set_footer(text=str(datetime.datetime.now()))
await ctx.channel.send(embed=purge_embed)
@Purge.error
async def Purge(self, ctx, error: commands.CommandError):
if isinstance(error, commands.MissingPermissions):
await ctx.send(f"{ctx.author.mention}You do not have permissions to do this command.")
!indents
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
must have no level of indentations
should be under the await?
^
even in a cog
that is how it is set
thats how it inherits everything in the cog since its in it
import os
import discord
import time
import datetime
import asyncio
from discord.ext import commands
class CMS(commands.Cog):
def __init__(self,client):
self.client = client
#Ping command
@commands.command(name='Ping')
async def Ping(self, ctx):
await ctx.channel.send(f"**pong!** That took {int(self.client.latency*1000)} ms!")
#Purge command
@commands.command(name='Purge')
@commands.has_permissions(manage_messages=True)
async def Purge(self, ctx, limit: int):
await ctx.message.delete()
await asyncio.sleep(1)
await ctx.channel.purge(limit=limit)
purge_embed = discord.Embed(title='Purge [%Purge]', description=f'Successfully Purged {limit} messages. \n Command executed by {ctx.author}.', color=discord.Colour.random())
purge_embed.set_footer(text=str(datetime.datetime.now()))
await ctx.channel.send(embed=purge_embed)
@Purge.error
async def Purge(self, ctx, error: commands.CommandError):
if isinstance(error, commands.MissingPermissions):
await ctx.send(f"{ctx.author.mention}You do not have permissions to do this command.")
#Help Command
@commands.command(name='Help')
async def Help(self, ctx):
embed=discord.Embed(title='Help Page!', description=f"%Ping (To tell you if I am online or not) \n %Purge (To purge mass messages) \n %Invite (Opens the invite page to invite me!) \n %Help (To open this page to tell you what commands I have)", color=0x206694)
await ctx.channel.send(embed=embed)
def setup(client):
client.add_cog(CMS(client)) ```
Can command_prefix be a list?
right i know that now i knew nothing about cogs when i started yesterday
yes
Ty
just classes lol
it is just classes
just basic subclassing lol
yw
just like that
ok i still have that error
try naming the function something else
in the error handler
and i have to check if error handlers are different in cogs
anything lol
ok at the @ part or just the def
and do @cog_Purge.error
in define in the function
yes should be like that
wdym
if not limit:
...
and add a default value of None
because that isnt the instance
right
Doesn’t work 🙈
where do i put that for indentaion reasons
on top
thats indentation
yes but no i can but i wasn't ready for it yet
^
wait nvm
you have to send the embed and return the function
in the if statement
thats all
ok here
Does the purge footer/datetime work?
probably does
yes
but use the timestamp kwarg
^
@commands.command(name='Purge')
@commands.has_permissions(manage_messages=True)
async def Purge(self, ctx, limit: int):
if not limit:
purge_failed = discord.Embed(title='Purge [%Purge]', description=f'Successfully Purged {limit} messages. \n Command executed by {ctx.author}.', color=discord.Colour.random())
purge_failed.set_footer(text=str(datetime.datetime.now()))
await ctx.channel.send(embed=purge_failed)
await ctx.message.delete()
await asyncio.sleep(1)
await ctx.channel.purge(limit=limit)
purge_embed = discord.Embed(title='Purge [%Purge]', description=f'Successfully Purged {limit} messages. \n Command executed by {ctx.author}.', color=discord.Colour.random())
purge_embed.set_footer(text=str(datetime.datetime.now()))
await ctx.channel.send(embed=purge_embed)
@cog_Purge.error
async def sendback(self, ctx, error: commands.CommandError):
if isinstance(error, commands.MissingPermissions):
await ctx.send(f"{ctx.author.mention}You do not have permissions to do this command.")```
must be one level in the if statement
and return the function
so it wont execute everything after it
wait so how do i set this right
wdym
you if statement
that is how code writes it out
ive said it many times
oh the if limit:
yes
and dont send the embed like that
return await ctx.send(embed=purge_failed)
it will return the function^
no need for the other if statement
if limit is none it will just return the function and if not it will just continue
no the other action you want to do you want it out of the if statement
can you rewrite it because i don't understand what ya mean
just delete a level of indentation after the return
yes but no need to do ctx.channel
just do ctx.send
and you can use the timestamp kwarg in the embed
when sending a msg
guess its the same decorator
ypu fixed that and it went
how do I make a member counter text channel? Whenever a member joins (on_member_join event), it updates the channel name to the number of members there are (+ the member that joined)
let me do tests
on the event just update the name and check the len of members
use get_channel to get the channel and use .edit to update the name ( wrong reply)
^
use get_channel to get the channel and use .edit to update the name
the part we just added didn't work at all i run same command i just don't get the error in the console
Name.of the class here?
async def interaction_check(inter) :
if inter.user != inter.author:
await inter.response.send_message("Just the author can click the buttons.", ephemeral=True)
return False
else:
return True
await interaction_check(inter)
why the check is not working
i have some buttons and i want to be clickable just by the author, i have no errors regarding it but just seems ineffective
I’ll be back to let yk
just pinged a random dude oops sorry
oopd
@client.event
async def on_message(message):
channel = client.get_channel(922582463241416756)
if message.channel.id == channel.id:
await message.add_reaction('✅')
await message.add_reaction('❌')
No Error: but the bot isn't adding this reactions?
you forgot self
so the if not limit didn't work
async def interaction_check(self, interaction: disnake.MessageInteraction) -> bool:
if interaction.author != self.author:
return False
return True
example ^
iirc syntax this should be correct?
so how do i make this work properly?
...?
or how do i do this?
to make it correct
i haven't used if statements with none before
but it's inside a command that already has self as first param, adding self it's starts throwing error
isnt interaction_check supposed to be in the button class
How do i add the default value as none?
so like this
i said in parameters
How do i set that i don't use parameters at all
!e
def function(arg: str = None):
if not arg:
return print("arg is None")
print("arg has value")
function()
@slate swan :white_check_mark: Your eval job has completed with return code 0.
arg is None
discord coding lol
^
please show me
limit: int = None
gitpod sadly but i also use vscode in white
the real vscode
no in parameters
def function(param)
chill out
😦 i dont wanna be a bitch but its timeconsuming even try help
i still like to help
so i got it
@slate swanam all for helping but kinda sucks when he dont have the wanna learn n try himself - and if no help, he ask about other commands that dosnt works
copypastabot
whats so hard to help tho?
if you have the knowledge why not bless someone with it?
I don't copy and pasta dude
its timeconsuming, and he dont even know indentations
ive always been told if you can bless someone then do it
not a big deal
ofc, but i would like to see him try learn basic python too
or he gonna ask for simplest thing 24/7
yes but whats so hard just to help him?
I already know basic python
and i haven't worked on my bot in idk 5 months
no u dont, u have no idea of indentations
@steel slate in the if statement it must be
if not limit
since limit is an argument and in parameters you should add
limit: int = None
which limit expects it to be an integer and has a default value of None
lol i do to i just don't know what goes into what why not give me a quiz and tell me what to make
its alright no need to fight we all know somethings others dont and thats why we help eachother
i tried help u, u could't even fix misspelled clent to client without upload code 2 times 😛
nah no problemos
that was a sight error
not a coding error
dont mind me 🙂
^
the answers to your problem are here
I don't understand i have put it the way i interpret that
if not limit: will nvr run
please send me the command
i got you
cause argument missing (parameter)
shut up please, i tried sub-classing the view and buttons , i ended up with something like
class View4(View):
@discord.ui.button(label='a', style=discord.ButtonStyle.blurple)
async def button_callback(self, button, inter):
await inter.response.edit_message(embed=embed1)
@discord.ui.button(label='b', style=discord.ButtonStyle.blurple)
async def button_callback(self, button, inter):
await inter.response.edit_message(embed=embed2)
@discord.ui.button(emoji='🗑️', label='Remove Buttons')
async def button_callback(self, button, inter):
await inter.response.edit_message(view=None)
the main problem was the embeds so i give up with this ngl
but u toss hair n fail n trail 😄 nothing wrong also how i do
well your missing an 2 inits
moved into a dm
@hoary cargo here -> https://github.com/DisnakeDev/disnake/tree/master/examples/views/button
don't have the same name for the functions
name them something differently otherwise they'll override each other
@commands.command(name='Purge')
@commands.has_permissions(manage_messages=True)
async def Purge(self, ctx, limit: int = None):
if not limit:
purge_failed = discord.Embed(title='Purge [%Purge]', description=f'Successfully Purged {limit} messages. \n Command executed by {ctx.author}.', color=discord.Colour.random())
purge_failed.set_footer(text=str(datetime.datetime.now()))
return await ctx.send(embed=purge_failed)
await ctx.message.delete()
await asyncio.sleep(1)
await ctx.channel.purge(limit=limit)
purge_embed = discord.Embed(title='Purge [%Purge]', description=f'Successfully Purged {limit} messages. \n Command executed by {ctx.author}.', color=discord.Colour.random())
purge_embed.set_footer(text=str(datetime.datetime.now()))
await ctx.send(embed=purge_embed)
@Purge.error
async def sendback(self, ctx, error: commands.CommandError):
if isinstance(error, commands.MissingPermissions):
await ctx.send(f"{ctx.author.mention}You do not have permissions to do this command.")
sorry i dont like helping in dms
ok it was just for the code
@hoary cargo button_a, button_b, would be something since u label has that a, b - for function names
its alr
i'd assign that .purge to a var and do Purged {len(the_var_name)}
since .purge returns a list of all the deleted messages
more accuracy
yeah i just helped him with params lol
:ASakashrug:
¯_(ツ)_/¯
i keep forgetting i don't have nitro anymore 😔
u poor
Why is my first event not going?
async def on_message(message):
if message.author == bot.user:
return
if "fdp" in message.content:
await message.channel.send(
f'{message.author.name}, qlf man swears at me :(')
await bot.process_commands(message)
@bot.event
async def on_message(message):
if message.author == bot.user:
return
if "sorry" in message.content:
await message.channel.send(
'ok man, you owe a picture of the dick')
await bot.process_commands(message)```
use
@bot.listen()
no, just don't wanna waste my money on nitro anymore lmao
was just joking 😛
better to use listen
bottom
yeah def kinda old use that
so how do i fix that so it works?
i gaved you the whole code?
^

see what i mean 😄
what is this for? I put it worked, I wanted to know what it's for to use this so the same error doesn't occur
just delete the old one and copy paste it
oh i didn't notice i thought it was mine that you moved into this channel
it just like event
but it doesnt overwrite itself on_message
lol
so i can use this in every event?
yes
thanks**
yw
si
before ya go i haven't changed it yet but it works i find this funny
what is the point of sending the command lol
what the hell, i need to take an english course, very bad translate ksksksk, bye
ciao have a good one
I'm a beginner, how do you make discord bots wait for a response?
discord bot is a bad beginner project
Beginner in bot development or in python overall
bot development
So you know python alright
oh well ok
ye i guess
!d discord.ext.commands.Bot.wait_for
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
sorry for not clarifying it
thanks
check documentation they have example of wait_for()
edit: click that link above ^
How long can it take a bot to get the history of a channel? I have it grabbing the history of a channel with 48.8k msgs and whilst i'm assuming it will take a while i'm just wondering if anyone knows a rough time it will take to completeNevermind, it took about 10 mins to do 48,869 msgs so that's 4,886.9 msgs per min, I think
😄
@flat solstice5k a min not bad?
83 msg a sec
@flat solsticemore important what api thinks about that?:D
aka limits
anyone know what's the request limit on disnake?
Ok so with the if command for the welcomer can i do print with the return to make sure it works?
Using a wait_for(), how do I check if the message was either yes or no?
for example, if I want confirmation from the executer that they want to run this command, how would I wait for it, and how would I check if it's yes or no
Check if the message.content was yes or no
Creating a delete all messages in a channel command (works by cloning the channel and deleting the last one), how would I go about it?
@bot.command(aliases=["nukechannel", "channelnuke", "n"])
@commands.is_owner()
async def nuke(ctx):
channel = ctx.channel
author = ctx.author
await ctx.message.delete()
await ctx.send(f"are you sure you want to delete all messages in {channel} (**y**/**n**")
...
@final iron
You just add it in your check
Have you used wait_for() before?
never
Ah
Have you checked out the docs?
They have examples
!d discord.ext.commands.Bot.wait_for
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
I have, but my particular situation doesn't work that way
How?
@client.event
async def on_message(message):
if message.content.startswith('$greet'):
channel = message.channel
await channel.send('Say hello!')
def check(m):
return m.content == 'hello' and m.channel == channel
msg = await client.wait_for('message', check=check)
await channel.send(f'Hello {msg.author}!')
This is checking content
and what about if it returns a no?
I want it to abort the command if its an n or no
i dont get it
@bot.command(aliases=["nukechannel", "channelnuke", "n"])
@commands.is_owner()
async def nuke(ctx):
channel = ctx.channel
author = ctx.author
await ctx.message.delete()
await ctx.send(f"are you sure you want to delete all messages in {channel} (**y**/**n**")
msg = str(bot.wait_for("message"))
iirc it returns a single argument/tuple of what the user said
yeah....
i still don't understand the check
Which part?
@bot.command(aliases=["nukechannel", "channelnuke", "n"])
@commands.is_owner()
async def nuke(ctx):
channel = ctx.channel
author = ctx.author
def check(m):
return m.content == #why am I doing a check if I'm going to do a check for yes or no?
await ctx.message.delete()
await ctx.send(f"are you sure you want to delete all messages in {channel} (**y**/**n**")
msg = str(bot.wait_for("message", check=check))
??
You need to define a check (function) and use the check kwarg
As shown in the example
check is defined
You need to have a check or else any user can say yes
And then it will wipe the channel
@bot.command(aliases=["nukechannel", "channelnuke", "n"])
@commands.is_owner()
async def nuke(ctx):
channel = ctx.channel
author = ctx.author
def check(m):
return m.author == author
await ctx.message.delete()
await ctx.send(f"are you sure you want to delete all messages in {channel} (**y**/**n**")
msg = str(bot.wait_for("message", check=check))
like that?
okok
But thats your choice
did it
@bot.command(aliases=["nukechannel", "channelnuke", "n"])
@commands.is_owner()
async def nuke(ctx):
channel = ctx.channel
author = ctx.author
def check(m):
return m.author == author and m.channel == channel
await ctx.message.delete()
await ctx.send(f"are you sure you want to delete all messages in {channel} (**y**/**n**")
msg = str(bot.wait_for("message", check=check))
if msg == "yes" or msg == "y":
...
elif msg == "no" or msg == "n":
...
like this?
!or
When checking if something is equal to one thing or another, you might think that this is possible:
if favorite_fruit == 'grapefruit' or 'lemon':
print("That's a weird favorite fruit to have.")
While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.
So, if you want to check if something is equal to one thing or another, there are two common ways:
# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
print("That's a weird favorite fruit to have.")
# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
print("That's a weird favorite fruit to have.")
fixed it @torn sail
like this?
@bot.command(aliases=["nukechannel", "channelnuke", "n"])
@commands.is_owner()
async def nuke(ctx):
channel = ctx.channel
author = ctx.author
def check(m):
return m.author == author and m.channel == channel
await ctx.message.delete()
await ctx.send(f"are you sure you want to delete all messages in {channel} (**y**/**n**")
msg = bot.wait_for("message", check=check)
if msg.content == "yes" or msg.content == "y":
...
elif msg.content == "no" or msg.content == "n":
...
Yep
So I have this command which I've asked a few questions about over the past few days and I thought I'd got it all functional but I've been running it today and it doesn't seem to be sending my embeds but it's also not giving me a error which makes me think it's a logic issue somewhere
https://srcb.in/Us46YHcqyf
I need help with a piece of code. I am creating a discord bot using python. This is my code:
import discord
import os
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
client.run(os.getenv('TOKEN'))```
But instead of saying "Bot Ready!" it gives me this syntax error:
```py
Traceback (most recent call last):
File "main.py", line 18, in <module>
client.run(os.getenv('TOKEN'))
are there any good libraries with components or should I start learning java?
why Java?
heya so i have a database for my bot setup (mongodb) but im not sure how to get it to get a custom prefix from the database itself?
can anyone help?
So I have this command which I've asked a few questions about over the past few days and I thought I'd got it all functional but I've been running it today and it doesn't seem to be sending my embeds but it's also not giving me a error which makes me think it's a logic issue somewhere
https://srcb.in/Us46YHcqyf
please anyone?
i havent done python in so long. how do i get the variable to increase with a command?
if you want it
put it inside the function
thats why it's a read line under it
other than that, im not sure what else
since ive never worked with global variables in discord.py
swearcount += 1 is a nice short way of incrementing it
thanks
all i know is it's supposed to be in a function like get_prefix
👍
your prefix
you call a command as so <prefix_goes_here>command_name
in discord.py scripts , in which part of code should i connect postgres db ?
i would need it mostly in some commands and on events like on_message , on_member_update , on_member_join etc.
i m new to db and sql so i need a bit clear info.
Ps : i read+know discord.py docs 💯 %
make a global var
Well you would create a bot variable
that to
!bot-var
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
bot var is better tbh
If its async then you make it in an async function
yup
like... on ready i load my db data to bot variable and after the day ends i would update the db with bot variable's data ?
noooooooooo
dont load your db on ready
do this
async def startup_function():
# load db......
#in the bottom of your file create the task
bot.loop.create_task(startup_function())
||ok , make a bot variable right
then what to do with conn=psycopg2.connect(params.)
where to be done ?||
ok i got it
is this a tasks.loop() process ?
wdym
btw you should add wait_until_ready
!d discord.ext.commands.Bot.wait_until_ready
no, this is a startup task, which you run after you declared your bot but BEFORE you run it
await wait_until_ready()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits until the client’s internal cache is all ready.
because you obv want the db to be ready BEFORE the bot goes online
no need for wait_until_ready()
oh yeah we arent changing status sorry
Hello, im trying this:
if cmd == 'amount':
f = open('data.txt', 'r')
for line in f.readline():
line = line.rstrip()
await ctx.send(line)```
for read every line and send it but its sending letter by letter of each line.
cause its a string
!e
a = "string"
print([b for b in a])
@slate swan :white_check_mark: Your eval job has completed with return code 0.
['s', 't', 'r', 'i', 'n', 'g']
in this case it will send it as a list
since its a list comprehension
!e
a = "string"
for b in a:
print(b)
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | s
002 | t
003 | r
004 | i
005 | n
006 | g
he probably meant readlines
by?
and how i can make change it?
well, readline, reads only one line
readlines reads all the lines
async def startup_function():
# load db......
#in the bottom of your file create the task
bot.loop.create_task(startup_function())
ok this will get my db ready ..
then i put some database's data in bot.variable ok!
do i have to connect/close to db in every way? like in on_message , on_member_join , on_xyz
or there is a correct way of doing that 🤔
closing the db will get trashed automatically once you terminate the bot
but you can overwrite the bot's "close" function if you want to do it explicitly
I highly suggest you to make like seperate "help/utils" for every DB function you want to execute, so you can easily reuse them
for example
async def all_members(self):
await self.db.execute("SELECT * FROM members")
shit = await self.db.fetchall()
return shit```
This can be a class which you extend your botclass with
i love your var naming
so you can easily call
db_members = await bot.all_members()
at least it's not user: discord.Member
lol
or member: discord.User
you got a point
equally as bad
yes
btw, forget what I said about the cursor, I forgot you don't really need them in an async db, you just straight up execute and fetch from the connection
(check docs for this ofc)
ok so to do operations on db i need a ctx manager
and what to do for db not be trashed?
trashed as in "it closes itself, no need to worry"
you don't per se, there are basic examples or quickstarters of your async db in the docs of it probably
there are .. but they use asyncpg and i m using psycopg2 ... i also a lill bit confused 😐
well, psycopg2 has docs too 🧠
You shouldn't use synchronous database adapters for Discord bots
2) ctx manager
3) psycopg2 docs
i'm gonna work on these 3 tonight.
thanks mates for all the helps 🙂
- not needed, but it's interesting to know what a context manager is tho
- asyncpg docs
Aah okay
Need help fixing something
client.counter = 0
client.this_dict = {}
@client.command(pass_context=True)
async def drink(ctx):
if (ctx.channel.id == 912562881684471810 or ctx.channel.id == 905601358562996244):
await ctx.message.delete()
client.counter += 0.02
if client.counter >= 0.15:
await ctx.send(f'You need to rush to the Hospital! {ctx.author.mention}')
if client.counter >= 0.40:
await ctx.send(f'You have died! You drank youself to the bottom of the barrel!')
client.this_dict[ctx.author.id] = client.counter
await ctx.send(f'{ctx.author.mention}\'s Blood Alcohol Concentration level is now {client.counter}')
await asyncio.sleep(60*(30))
client.counter = 0
This is apparently mixing up people's counters
So if, for example, I do -drink
It'll increase to 0.02
yeah, everyone uses the same counter...
you obviously want a different counter per user
Umhmm, but i set the author's counter to the dict?
shoudnt they all be registered differently?
nope
access the counter like this_dict[user_id]
that'll return the counter of that user
also, since you're not using a DB, I suppose you don't care if when the bot restarts, data is lost?
Well, the values resets after 30 minutes anyways so no point of using a data base
aight
anyways, first thing to do in that command is make sure the user has a counter in that dict
if he doesn't, add one and set it to 0
@client.command()
async def checkbac(ctx, *, arg : discord.Member):
if (ctx.channel.id == 912562881684471810 or ctx.channel.id == 905601358562996244):
await ctx.message.delete()
if arg.id not in client.this_dict:
return await ctx.send(f'{arg.mention} has a Blood Alcohol Concentration Level of: 0.00')
await ctx.send(f'{arg.mention} has a Blood Alcohol Concentration Level of {client.this_dict[arg.id]}')
if client.this_dict[arg.id] >= 0.15:
await ctx.send(f'{arg.mention} needs to be rushed to the Hospital!')
also, let's shorten it up
This is to check someone's counter
if arg.id not in client.this_dict:
return await ctx.send(f'{arg.mention} has a Blood Alcohol Concentration Level of: 0.00')
if ctx.channel.id in (912562881684471810, 905601358562996244):
alright, just know that you shouldn't use client.counter, but the dict instead
like user_alcohol_counter = {}
and once filled, it should look like
{ 123456: 0,
155151: 0.5
}```
Umhmm
The counter increases by each command and registers it in dict, you want me to get rid of the counter?
I'm a little confused by what you mean?
I understand this is what the dict should look like when storing the values yes
you should just have a counter per user, not a global counter which everyone uses
SO create a counter within the command?
no, just only use the bot.counter_dict
or whatever that dict is
you don't need the bot.counter, since everyone can access that...
do when you drink, it sohuld should look like
client.counter_dict[ctx.author.id] += 0.05
or whatever your values are
you count numbers by 0.05?
idk lol ,you count them with .15 sometimes lol
So get rid of the global counter, and make the dict count?
interesting
yeah, just only count PER user, as said earlier
But wait a sec
client.counter = 0
client.this_dict = {}
@client.command(pass_context=True)
async def drink(ctx):
if (ctx.channel.id == 912562881684471810 or ctx.channel.id == 905601358562996244):
await ctx.message.delete()
client.counter += 0.02
if client.counter >= 0.15:
await ctx.send(f'You need to rush to the Hospital! {ctx.author.mention}')
if client.counter >= 0.40:
await ctx.send(f'You have died! You drank youself to the bottom of the barrel!')
client.this_dict[ctx.author.id] = client.counter
await ctx.send(f'{ctx.author.mention}\'s Blood Alcohol Concentration level is now {client.counter}')
await asyncio.sleep(60*(30))
client.counter = 0
Shouldnt the counter reset bc of client.counter = 0 at the end?
.
I'm doing that as well, but thinking about the logic, shouldnt the counter reset?
client.this_dict[ctx.author.id] = 0
that's how you would reset the counter FOR THAT USER
Welp, I am a total dumbass. I understand now
actually deleting the value might be a better idea, since you don't want hundreds of key values where the counter is just 0, only add them if it's not 0 or whatever
also, check out "command checks", this is basically a replacement of your outer if statement
Understood
or even better
use cogs (this categorizes commands, tasks and events), and use a cog check
that way, you don't have to use a command check for every command
since I suppose you can only run certain commands in the same 2 channels
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: unsupported operand type(s) for +=: 'dict' and 'float'
code?
@client.command(pass_context=True)
async def drink(ctx):
if ctx.channel.id in (912562881684471810, 905601358562996244):
await ctx.message.delete()
client.this_dict += 0.02
if client.this_dict[ctx.author.id] >= 0.15:
await ctx.send(f'You need to rush to the Hospital! {ctx.author.mention}')
if client.this_dict[ctx.author.id] >= 0.40:
await ctx.send(f'You have died! You drank youself to the bottom of the barrel!')
#client.this_dict[ctx.author.id] = client.counter
await ctx.send(f'{ctx.author.mention}\'s Blood Alcohol Concentration level is now {client.this_dict[ctx.author.id]}')
await asyncio.sleep(60*(30))
client.this_dict[ctx.author.id] = 0
crap
ik how to fix 1 sec
client.this_dict += 0.02
this is ofc the problem
You can remove pass_context=True
This was necessary a few years ago when discord.py was created, not anymore
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 439875622626394122
that's a very english error
make sure the key is in there before adding shit to it ofc
client.this_dict[ctx.author.id] = 0.02
Yea adding an if statement that will set the user's number to 0 before doing the command
do what you like
Will that be incorrect?
will work, but not the best method
Oh, what would be the best thing to do?
I'd do like:
if drank too much, remove from dict
if he uses the drink command again
if not in this_dict, then this_dict[author.id] = 0.02
since the first drink, he has 0.2 apparently
then, if you want to check someone's alcohol level
if he's not in the dict => his alcohol level is 0
else: do other shit
also, use elif
you're also literally resetting someone's alcohol lvl after every drink
You can do client.this_dict.get(arg.id, 0) then send that as the current BAC
Thus allowing for a default value if arg.id does not exist in the dict
right, that'll shorten this up
Hello! i am trying to make a rob commands but i cannot not get it to send the messages can you guys please help me. There is no error showing.
@commands.command()
async def rob(self,ctx,member:nextcord.Member):
await open_account(ctx.author)
await open_account(member)
bal = await update_bank(member)
authorBal = await update_bank(ctx.author)
if bal[1]<5000:
await ctx.send("No point robbing this one, sweet child <3, leave them be them be they are saving up, and they dont have $5000 ;-;")
return
if authorBal[1]<5000:
await ctx.send("No point robbing you dont have $5000 ;-;")
return
earnings = random.randrange(20, bal[0])
bad_luck = random.randrange(20, authorBal[0])
Truth = []
c = random.choice[earnings, bad_luck]
Truth.append(c)
if Truth[earnings]:
await update_bank(ctx.author,earnings)
await update_bank(member,-1*earnings)
await ctx.send(f"You stole ${earnings}, Lets hope they dont want revenge")
if Truth[bad_luck]:
await update_bank(ctx.author,-1*bad_luck)
await update_bank(member,bad_luck)
await ctx.send(f"You lost ${bad_luck}, teaches you right")
indeed
Is it entering the if statements?
i dont think so
There's your issue
But i dont know how to fix that?
your if statements are unreachable
how do i make them reachable? sorry for the dumb questions
don't follow stinky YT tutorials first of all
^
Half of that came from tutorial
I added the lists to choose between earnings and badluck
the if statesment become unreachable
For example, if you followed half of what freecodecamp tutorials said, you'd be fucked.
no cap
well that's even worse
to try and make the money go into the oppiste account
it worked before i added stuff
That means you don't understand what you are doing
its an issue with your code
What are you trying to do below the randranges
that you added
it choose the balance being taken out of the account
and added to another
What is Truth and bad_luck
Bad luck takes the balance out of the robber.
the truth variable chooses between the earnings and badluck
it chooses the path for the robber
whether it fails
or it succeeds
terrible varnames, sorry xd
ik
Yeah, your code is very unreadable so it makes helping quite difficult. But what you are doing in the if statement is indexing a value from 20-5000+. It'll raise an indexerror
but wouldnt it send an error of thats the case?
@quaint scaffold :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | IndexError: list index out of range
Not sure why you don't see any errors
that what im confused about
ive been meddling with it but how would i make it work?
im sorry of im being annoying
Just use a tuple when you make the randrange
Is there a way I can make my bot check if a user used a certain slash command from a different bot?
you could try an on_message and look there maybe
on_message would detect the message sent by other bot on using the command , but not the invocation message from user
doesnt detect the /ping , but detects the response from bot
idk about other libraries but Disnake (or mb discord.py itself) has Message.interaction to check if message was created with some interactions
Message.interaction.type will return application_command if it was sent in response to a slash cmd
^^^
So how do you print perms it has for each guild on startup?