#discord-bots
1 messages · Page 27 of 1
👁️ 👁️ 👁️
statically typed😳 😏
pretty basic atm
lol
no model folder?
but you have to
ik but I dont

then what do you want?
cause no models yet
that's why I asked here if someone would be able to help explain it?
what explain
pigeon, how experienced are you with python?
but you have a PartialUser/Base obj?
not very tbh...
!resources Do i send it?
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
hm?
i didnt even notice that i commited it lol
and pushed
yeah, sadly
tehe, maybe i can help you with model implementation👀
How can I cancel a command from executing through on_command?
@bot.event
async def on_command(ctx):
if ctx.invoked_with == ...: # Meets some condition
# cancel command from executing
wtf im scrolling page up but it returns me back to where i was
ngl, the events are inspired by hikari
except for the single time listeners
I'd really appreciate that
sure ill help when you make base objs etc
was this for me?
yes
yeah im working on The RESTClient rn
alright honey
so what do I do now?
learn python?
all I need to know is this one question and I'll be on my way
wdym? you need to use this to learn how to use slash commands?
PreviousButton = nextcord.ui.Button(emoji:id=1006237375938179142)
could someone help me format buttons correctly? im just trying to set the button to the ⬅️emoji
You can pass that in as a string to the label kwarg
#databases anyone?
why doesn't my bot have a description even though i entered one?
does anyone know what this error means?
You may be on an older version of python that doesn’t support this type
how do i upgrade to the latest version of python?
#databases anyone
It heavily depends on your OS/package manager. Windows and MacOS, I honestly can't tell ya. On linux, you'd just upgrade the package with your package manager as you would any other
One good thing about Arch is I don't have to worry about updating my Python, it's always bleeding edge 😄
you use arch no gui?
bspwm
ohh, nice
i use windows vista
from __future__ import annotations
list[discord.Embed]
# or,
import typing
typing.List[discord.Embed]
updating python would be the best choice
yeah iirc __class_getitem__ was impl in 3.9
im in pycord and i can't seem to have my OptionChoice show up at all. im trying a test command but it still isn't showing up,
classes_list = [
OptionChoice(name = 'Tank', Value = 'Tank'),
OptionChoice(name = 'Assassin', Value = 'Assassin'),
OptionChoice(name = 'Fighter', Value = 'Fighter')
]
#
async def poopingtest(ctx, classes: Option(str, 'Class choice', choices = classes_list)):
@commands.command()
async def addname(self, ctx, name):
e = conn.cursor()
x = ctx.author.id
y = name
e.execute('''INSERT INTO names
(user, name)
VALUES (?, ?);''',
(x, y))
conn.commit()
await ctx.send("Registered")
@commands.command()
async def deletename(self, ctx, name):
e = conn.cursor()
x = ctx.author.id
y = name
e.execute("""DELETE FROM names WHERE user = ? and name = ?;""", (x, y))
conn.commit()
await ctx.send(f"{name} successfully deleted")
@commands.command()
async def name(self, ctx, name: discord.Member):
e = conn.cursor()
id = name.id
e.execute("""SELECT name FROM names WHERE user= ?;""", (id,))
await ctx.send(e.fetchall())
@commands.command()
async def namelist(self, ctx):
e = conn.cursor()
e.execute("""SELECT name FROM names""")
await ctx.send(e.fetchall())```Hi I'm having a problem with my sqlite3 database, I made it so that I can store contents inside of the database via a discord bot / commands, and it stores them perfectly and retains them, but every day the table contents reset apart from the ones MYSELF has set
@bot.command(pass_context=True)
async def meme(ctx):
embed = discord.Embed(title="", description="")
async with aiohttp.ClientSession() as cs:
async with cs.get('https://www.reddit.com/r/dankmemes/new.json?sort=hot') as r:
res = await r.json()
embed.set_image(url=res['data']['children'] [random.randint(0, 25)]['data']['url'])
await ctx.send(embed=embed)
the code isnt working
like it isnt sending out the meme
this error comes:
Ignoring exception in command meme:
Traceback (most recent call last):
File "/home/runner/Astro/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 16, in meme
async with aiohttp.ClientSession() as cs:
NameError: name 'aiohttp' is not defined
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/Astro/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/Astro/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/runner/Astro/venv/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: NameError: name 'aiohttp' is not defined
how do i define it?
ohk
python doesn't wanna respond ig 
https://pypi.org/project/aiohttp/
!pypi aiohttp
does not work so what should i do?
its like you possess skill issues
huh?
it isnt installing
or maybe python doesnt like you
how do i install it
bro it responded now. wtf
how did it got delayed so hard😭
it says it right there
ohk wasnt loading for me
Why do you need to install aiohttp
Aiohttp comes with discord.py
It's a dependency, just import it
If you didn't have it installed and actually did import you'd get ModuleNotFoundError but your getting a NameError here meaning you never even tried importing
#databases anyone I've been waiting for 2 hours
did i mess up on the format for this? i'm not even getting any options showing up when i type the command
``async def poopingtest(ctx, class_choice: option(str, 'Class choice', choices = classes_list)):`
also tried with capital Option
Tried earlier got this message for some reason :/
Do note: I'm using Visual Studio Code.
have you added your python path to your environments variables?
When trying to install a package via pip, it's recommended to invoke pip as a module: python -m pip install your_package.
Why would we use python -m pip instead of pip?
Invoking pip as a module ensures you know which pip you're using. This is helpful if you have multiple Python versions. You always know which Python version you're installing packages to.
Note
The exact python command you invoke can vary. It may be python3 or py, ensure it's correct for your system.
How to do embed pagination?
well, do you?
I installed git
where does it say about PATH
??
how can i make a mute command like dyno? That it gives the user a timeout?
if that runs, its added to PATH ~
ohkay
!d discord.Member.timeout
await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.10)").
You must have the [`moderate_members`](https://discordpy.readthedocs.io/en/latest/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/latest/api.html#discord.Member.edit "discord.Member.edit").
im too late(
thanks
I was thinking of it but I decided to check in docs if that is time_out or timeout
client = commands.Bot(command_prefix=commands.when_mentioned or (config["prefix"]), intents=intents ) why my prefix dont working?
its disable_communication_until at API level
?
commands.when_mentioned_or(configs["prefix"])
why this or ?
!d discord.ext.commands.when_mentioned_or
discord.ext.commands.when_mentioned_or(*prefixes)```
A callable that implements when mentioned or other prefixes provided.
These are meant to be passed into the [`Bot.command_prefix`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.command_prefix "discord.ext.commands.Bot.command_prefix") attribute.
Example
```py
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'))
```...
how can i make it that its automatically minutes? and not 0:00:00?
does import discord still exist?
???
yes
just use seconds attribute of timedelta and divide by 60
Yes, have you installed dpy
whats the command to install it?
pip install discord.py
👍
please install 2.0
python -m pip install git+https://github.com/Rapptz/discord.py
Bruh where are you running it
wdym
The command
pip isn't on your path, you'd have to search the pip folder in your python folder and add it to path
or use python -m pip
python or py is most probably on your path
you probably need to use a virtual env
you don't even have python...
i do
lemme check
no matching commands
what exactly do i do after ctrl shift p
do as the terminal said and run
python
i dont understand
How can I add choice to slash command as user id?
which ide is that?
looks like pycharm to me
it's 100% pycharm
yeah
From what I remember it's "Python: Select Interpreter" and seems like vsc command pallet search is not smart
@tame raft just reinstall python but put the Add Python to PATH checkmark when installing
😭
yh thx, i did that
it worked
👍
why can I still type? I dont have any perms or other roles
His name is very sus doe
Permissions issue
Probably like everyone role has explicit send message perm set to true
Also look at the underlines and pay attention to the recommendations, they'll make your code better
Pycharm is so great for improving code style imho
I am making a ban command for my bot, and I realised when I manually try to ban somebody, I can give a reason and a Delete Message History option. How can I implement the same feature so the bot specifies it?
!d discord.Member.ban
await ban(*, delete_message_days=1, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Bans this member. Equivalent to [`Guild.ban()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.ban "discord.Guild.ban").
thanks
How do people adequately test discord bots (automation wise) without the ability to allow a bot to create a server?
Just having a test server and cleaning up data each time?
What do ya mean?
I have a bot with slash commands, I want to test the slash commands in an automated fashion, E2E, instead of manually
I guess I could unit test the methods without issuing a slash command but then is there a way to mock an interaction object? Or would you just have a bot issue slash command to itself?
is this REST or WS based?
@night crater is your pfp ashley rosemary?
No comment
I'm pretty sure it is 😳
And how would you know that 👁️

how can i get the ids of which user joins the server
So I have a list, how could I make it so I have like 4 items per page on an embed? I have never used embed pages
2.0 api link
🤔
if user is None:
user = ctx.author
try:
bal = await economy.find_one({"id": user.id})
if bal is None:
await self.open_account(user.id)
bal = await economy.find_one({"id": user.id})
embed = discord.Embed(
timestamp=ctx.message.created_at,
title=f"{user}'s Balance",
color= random.choice(colors),
)
embed.add_field(
name="PAOD's",
value=f"${bal['PAODs']}",
)
embed.set_footer(
text=f"Requested By: {ctx.author.name}", icon_url=f"{ctx.author.avatar_url}"
)
embed.set_thumbnail(url=user.avatar_url)
await ctx.send(embed=embed)```
py 2.0 // whats wrong ??
!d discord.on_member_join
discord.on_member_join(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") joins a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
well, do you have an except anywhere?
If I remember correctly you cannot have a try without an except block
try:
# do something
except some_error:
# error, do something
is anyone error raising? @limber bison
i have an except block i didnt copy here !!]
hehehe
Well what's the error?
try:
bal = await economy.find_one({"id": user.id})
if bal is None:
await self.open_account(user.id)
bal = await economy.find_one({"id": user.id})
embed = discord.Embed(
timestamp=ctx.message.created_at,
title=f"{user}'s Balance",
color= random.choice(colors),
)
embed.add_field(
name="PAOD's",
value=f"${bal['PAODs']}",
)
embed.set_footer(
text=f"Requested By: {ctx.author.name}", icon_url=f"{ctx.author.avatar_url}"
)
embed.set_thumbnail(url=user.avatar_url)
await ctx.send(embed=embed)
except Exception:
await ctx.send('An error occured')```
What's the error
raise the exception
my bot has ```<p>The owner of this website (discord.com) has banned you temporarily from accessing this website.</p>
did my bot baned from
discord..
iirc replit uses shared IP's so it could've been some other person spamming the api
Not using replit
can you recommend some cheap hosting sites?
or is it forbidden
Does discord-ext-menus works with discord.py 2.0?
@gusty shard read this
thanks
proof y9 knows everything
discord.ext.commands.errors.ConversionError: (<class 'commands.pvc.pvc.DurationConverter'>, TypeError("new() missing 3 required positional arguments: 'name', 'bases', and 'namespace'"))
class DurationConverter(commands.Converter):
async def convert(self , ctx , argument):
amount = argument[:-1]
unit = argument[-1]
if amount.isdigit() and unit in [ 'm' , 'h']:
return (int(amount),unit)
raise commands.BadArgument(message='Not a vaild duration')
```
is this ok in py2.0 ?
Like a everyone?
Any role
hmm I would say yes but I have not tested it so
Yes
Hello, anyone that could offer advice?
I have a Discord bot that was made a very long time ago. I know the password as I use the same handful for everything, but I cannot for the life of me remember what email I used. Is there any way at all to find out what this is, or is my only option remaking the bot?
I do still have access to all the code, as it is hosted on Repl.it
The discord bot should be tied to your account, should it not?
Can you log into your account on the development portal?
It is tied to a unique account made for the bot, not my account
Ah okay. If you forgot your email I don't think there's a way to reset it, you could try contacting support
gotcha, this is what i figured. I suppose it wont be too much of a hassle to just copy/paste the code into a new bot, just annoying
or actually, if I make a new bot, all I would have to do is change the token, yea?
Does anybody know how to setup a keyauth system with a bot is it easy?
also hi robin idk if you remember me
Can you enable searching / typing in the placeholder part of a discord select field ?
We talking about discord here lmao
Ok so I'm just stupid, it was connected to my account lol, thats why i couldnt find the email
So it seems my bot has been temporarily banned because of rate limit. tried resetting the token to make sure it wasnt just an error, but yup, same errors
How do I go about fixing this? I'm not even sure how we could be exceeding rate limits, the bot has nothing but text commands
Are you using replit?
yes
await client.wait_for('message', check=check , timeout = 10) ??
is this ok ? error !!!
What's the error?
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: loop attribute cannot be accessed in non-async contexts. Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hook
😳
@sick birch sir ?
!d discord.Client.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.10)"). 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.10)") 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.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
docs don't say anything
mind sending the traceback?
Is there a way to have an empty embed title? In this image I tried using \u200b that's supposed to be an empty character but It still renders that empty space
Why not use an embed field instead?
!d discord.Embed.add_field
add_field(*, name, value, inline=True)```
Adds a field to the embed object.
This function returns the class instance to allow for fluent-style chaining. Can only be up to 25 fields.
It's okay
thanks btw fixed
1 question
how can i remove a member from channel permission list
set_permissions set the pems but how to remove ??
Could discord ever end up having guild ids or role ids over 19 integers?
No right? That's the max a database cold hold w a BIGINT?
they can be strings
How to add a role if they don't already have, and remove it otherwise? (IE a toggle)
Is there a clean / abstract way without doing checks on the user? In discord py
If they have role:
remove it
else:
give it
You can reload all cogs if that's close enough
Hey! My mute command should setup a muted role with that the user cant write messages anymore and it should setup the channels but it doesnt and i can still type with my alt account, i have no permissions, the bot has permissions to everything
Issue: My help command does not respond whatsoever and I also get no errors.
Code: https://mystb.in/ArePrideMortgage.python
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
I have all intents enabled :)
It’s only my help command that doesn’t work, all other prefixed commands are functional.
Ah, good to know. Got any error handlers?
Also looks like your help command is indented inside of the Help constructor
Yep, I have a events cog for all my command errors. None are returned though.
Yeah, it’s a cog?
Right, the issue is because your command is indented inside the constructor, so discord.py never picks it up
All cog commands are supposed to be indented into the cog class, no?
Commands within cogs should look like so:
class MyCog(commands.Cog):
def __init__(self, ...) -> None:
...
@commands.command()
async def my_command(self, ctx: commands.Context, ...) -> None:
...
not like this:
class MyCog(commands.Cog):
def __init__(self, ...) -> None:
...
@commands.command()
async def my_command(self, ctx: commands.Context, ...) -> None:
...
^ which is what yours looks like
for some reason the system thinks "import discord" isnt valid. (it was fine earlier)
You're running it in the REPL mode
Type out exit(), then go about it as usual
thx
I have a bot with a select field that needs to go over 25 options. Can anyone send me a good guide of a decent solution maybe involving paging and buttons?
Selects natively can hold 25 options, if I'm not wrong
How do I check for HTTP exception 429 specifically with try, except?
Correct, what's the best way to bypass this?
Including buttons to page right?
Ah, you've got more than 25 options?
Yes hehe
Hm. Might be better to just have a user input a number to select something, instead of a full on select/button pagination thing
Aaaaaaa, I've been trying to fix this for just about 2 hours 😂. Thank you very much :)
can someone help me please?
The number of options can theoretically grow very high, I want to avoid the scenario of having a giant message
Basically, the bot allows server members to follow artists on spotify. Then it pings new releases to those who are assigned to the role it created. People can self-assign roles for the server's followed artists through the select menu at the moment
Right, okay. No good guides for this sort of thing as it's pretty complex, but what you can do is edit your current view with a completely new view that looks identical, except the select options are different, the next 25 in your list
So say you had a select with options 1-5, user presses the "next" button, edit the message with the same view, but options 6-10, etc
And how to reach that new view? The press of a button?
Yeah, you'd handle that inside of the button press callback
Any idea what's going on here?
Including that line makes offset an unresolved variable
Any idea about putty ?
Like if want to edit something on awe I need to reupload right ?
is offset defined in your global scope?
This is a function within a method, and offset is defined above it yes
Like if I do this
offset = 25
async def page_select_forward(ctx: discord.Interaction):
if offset == 25:
view.add_item(prev_button)
select.options = select_options[offset:offset+25]
offset += 25
ctx.response.defer()
Basically, trying to add 25 to offset is causing that error
otherwise, no error
ah, yes, offset is in your global scope, and you're trying to change the value of a global scope variable in a local scope variable. You can't do that. You have to make offset global inside your local scope.
You can still access global variables inside a local scope, hence why everything was alright until you added the offset += 25 bit
If it's inside of a view or button subclass (which I suspect it is), you can bind it to self and access and write to it
Error:
Ignoring exception in view <HelpView timeout=180.0 children=1> for item <Select placeholder='Please select a category:' min_values=1 max_values=1 options=[<SelectOption label='Owner' value='Own' description='Select to view our Owner commands.' emoji=<PartialEmoji animated=False name='CL_AzielOwner' id=1000907171959161023> default=False>, <SelectOption label='Moderation' value='Mod' description='Select to view our Moderation commands.' emoji=<PartialEmoji animated=False name='CL_AzielMod' id=1000909301927395358> default=False>, <SelectOption label='Information' value='info' description='Select to see our infomational commands.' emoji=<PartialEmoji animated=False name='CL_Book' id=1000145556204691536> default=False>, <SelectOption label='Fun' value='Fun' description='Select to view our Fun commands.' emoji=<PartialEmoji animated=False name='CL_AzielGames' id=1000908640263344178> default=False>] disabled=False>:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.9/site-packages/discord/ui/view.py", line 371, in _scheduled_task
await item.callback(interaction)
File "/home/container/cogs/help.py", line 44, in select_callback
owner_cog = self.get_cog(name='Owner')
AttributeError: 'HelpView' object has no attribute 'get_cog'
how do i get a webhook with a specific name without having to iterate through all the channel webhooks
from mysql import connecter
idk
oh
Did you install the package?
you forgot the self in my_command
to heck with pylance
it doesn't work half the time
continue anyway
i dunno
in pycharm you would just recheck for all errors and scan all packages again
no clue abt vsc
Using and setting up a venv fixes up 99% of module importing errors
How to check how many servers the bot is running on every 5 minutes?
Make sure you've got a MySQL server running on that machine and port, port forward if you have to. Configure your firewalls to let any packets in, make sure your username/password and any other authentication is correct
Better suited towards #databases. I myself have never worked with mysql
DROP TABLE discord-messages;
sorry im new to python but anyone knows why im not being responded to?
import random
import discord
client = discord.Client()
@client.event
async def on_ready():
print(f'{client.user.name} has connected to Discord!')
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content == "!randomnumber":
await message.channel.send(message.author.display_name + " your random number is \n" + str(random.randint(1, 500)))
client.run("-_-")
How to check how many servers the bot is running on every 5 minutes?
!d discord.ext.commands.Bot.guilds
property guilds```
The guilds that the connected client is a member of.
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
how to check it every 5 minutes?
!d discord.ext.tasks.Loop
class discord.ext.tasks.Loop```
A background task helper that abstracts the loop and reconnection logic for you.
The main interface to create this is through [`loop()`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.loop "discord.ext.tasks.loop").
@tasks.loop(seconds = 5)
async def myLoop():
numofservers = len(bot.guilds)
activity = discord.Game(name=f'Watching {numofservers} servers', type=1)
await bot.change_presence(status=discord.Status.online, activity=activity)
myLoop.start()``` is this code correct?
can anyone help me make a disscord bot plz ?
LGTM
yeah it doesn't work
import random
import discord
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
client = commands.Bot(command_prefix='!')
@client.event
async def on_ready():
print(f'{client.user.name} has connected to Discord!')
@client.event
async def on_message(message):
if message.author != client.user:
if 'randomnumber' == message.content:
embed=discord.Embed(title="Random Number!", description=message.author.display_name + ", your random number is " + str(random.randint(0,1000)), color=0x8bc34a)
await message.channel.send(embed=embed)
await client.process_commands(message)
client.run("")
what does lgtm mean
await self.coro(*args, **kwargs)
File "main.py", line 184, in myLoop
await bot.change_presence(status=discord.Status.online, activity=activity)
File "/home/runner/EskusemeBot/venv/lib/python3.8/site-packages/discord/client.py", line 1062, in change_presence
await self.ws.change_presence(activity=activity, status=status, afk=afk)
AttributeError: 'NoneType' object has no attribute 'change_presence'``` got this error @sick birch
Make sure you've got message_content intent
Might want to want until the bot is ready, see this example straight from the docs:
from discord.ext import tasks, commands
class MyCog(commands.Cog):
def __init__(self, bot):
self.index = 0
self.bot = bot
self.printer.start()
def cog_unload(self):
self.printer.cancel()
@tasks.loop(seconds=5.0)
async def printer(self):
print(self.index)
self.index += 1
@printer.before_loop
async def before_printer(self):
print('waiting...')
await self.bot.wait_until_ready()
do this?
intents.message_content = True
Right
still doesn't work :/
ohhh
wait what?
import random
import discord
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
intents.message_content = True
client = commands.Bot(intents.message_content = True, intents.members = True,command_prefix='!')
@client.event
async def on_ready():
print(f'{client.user.name} has connected to Discord!')
@client.event
async def on_message(message):
if message.author != client.user:
if 'randomnumber' == message.content:
embed=discord.Embed(title="Random Number!", description=message.author.display_name + ", your random number is " + str(random.randint(0,1000)), color=0x8bc34a)
await message.channel.send(embed=embed)
await client.process_commands(message)
client.run("")
How can i make it so it only sends the message once only? Either when member is None or; when time is None
liike this?
no, exactly how i showed; intents=intents, not intents.members=True
should I add the code after on_ready ?
(the latter is invalid syntax)
intents.members = True
intents.message_content = True
then you'd pass in intents into the constructor, nothing special
You're instantiating a class, changing properties/flags, whatever you want to call it, then passing the same class into the bot's constructor
this should be it then right?
intents = Intents.default()
intents.members = True
intents.message_content = True
client = commands.Bot(command_prefix='!' + intents)
!resources I think learning python itself can only help you, because right now it seems more of a hindrance. I don't mean to turn you away, but put discord bots on hold for a little bit as they're complex and require a good bit of Python knowledge
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
thank you for your help, ill try reading more up on it
@sick birch
Can I have a prefix command redirect to a slash command, just by passing in the interaction object and manually calling the method?
Slash commands need to be directly invoked by the user. You can try to invoke the handler manually, but you'll have to manually pass in the arguments
No, this one is seperate from on_ready. Just use wait_until_ready
inside the @task?
Right, see how it's done in the example. Do just like that.
class MyCog(commands.Cog):
def __init__(self, bot):
self.index = 0
self.bot = bot
self.printer.start()
def cog_unload(self):
self.printer.cancel()
@tasks.loop(seconds=5.0)
async def printer(self):
numofservers = len(bot.guilds)
activity = discord.Game(name=f'Watching {numofservers} servers', type=1)
await bot.change_presence(status=discord.Status.online, activity=activity)
@printer.before_loop
async def before_printer(self):
print('waiting...')
await self.bot.wait_until_ready()``` should be this?
That should cut it, make sure to change the names because "printer" is not an appropriate name for your method's usecase
seems doesn't work, I added the bot to a server and waited for a minute but nothing changed.
@deep osprey why did you define bot in your Cog file again, you need to use self.bot wherever you need to acess the bot inside a cog class
ok I did that but the same thing
@slate swan @sick birch so any solution?
I am making a discord currency bot and want to store the data in a json file but i am getting a weird error
here is my code
import discord
from discord.ext import commands
import json
bot = commands.Bot(command_prefix=">", intent=discord.Intents.all())
@bot.event
async def on_ready():
print("JOE TO GOOO...")
@bot.event
async def on_message(message):
user_id=str(message.author.id)
with open("jardb.json", "r") as f:
jar=json.load(f)
if user_id not in jar:
jar[user_id]["cookies"]=0
with open("jardb.json", "w") as f:
json.dump(jar, f)
bot.run(token)```
error:
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\8ster\Desktop\projects\Discord Bots\Novicookies\main.py", line 18, in on_message
jar[user_id]["cookies"]=0
KeyError: '988763812272422952'```
are there any differences on using pycord speed compared to using none?
CPU usage wise? o
you are literally checking if user_id is NOT in jar and then if it is NOT it jar, you're trying to get it...
hmmm...
I don't have idea what are u talking about?
can u give me the code sample
like what u actually mean
hmmm... im talking about your code
if user_id not in jar:
jar[user_id]
how to fix it?
don't do jar[user_id] when it's not in jar?
then if it's not in jar i need to store it right?
if you are trying to set jar[user_id] to something, then do jar[user_id] = something
ohhh ic ic let me try it
not jar[user_id]["cookies"]=0
can u set something value to 0?
you can set something to whatever you want
Master how can I add or subtract something's value?
so you got jar[user_id] = 0, right?
that will not work
jar[user_id] = {"cookies": 0} this would work
how can i add/subtract cookies's value
+= operator
like jar[user_id]["cookies"] += amount
or -= for subtract
MASTER thanks a looot!
i think i messed up again
from http import cookies
import discord
from discord.ext import commands
import json
bot = commands.Bot(command_prefix=">", intent=discord.Intents.all())
@bot.event
async def on_ready():
print("JOE TO GOOO...")
@bot.event
async def on_message(message):
user_id=str(message.author.id)
with open("jardb.json", "r") as f:
jar=json.load(f)
if user_id not in jar:
jar[user_id] = {"cookies": 0}
with open("jardb.json", "w") as f:
json.dump(jar, f)
else:
jar[user_id]["cookies"] += 5
with open("jardb.json", "w") as f:
json.dump(jar, f)```
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\8ster\Desktop\projects\Discord Bots\Novicookies\main.py", line 23, in on_message
jar[user_id]["cookies"] += 5
TypeError: 'int' object is not subscriptable```
...
anyone knows how can i make a login system; eg. login for a custom role that has some unique perms
you've already set your jar[user_id] to 0 before, and since you are not rewriting it you are trying to get ["cookies"] from 0, not from {"cookies": 0}, so you'd better go to your json file and just clear it (make it's content {})
what do you mean login system?
if you mean requiring a password to get a certain role, you can do this via a Modal, this exists in both hikari and d.py
under the callback, have it check if the response == password, then use the add_role method, that is in your library
What is this error 😳
It happened after I added self.tree.copy_global_to(guild=discord.Object(id=980346257371455528)) to slash commands setup, but when I remove it, this error is still here
TypeError: Object of type _MissingSentinel is not JSON serializable
maximum recursion depth error means your code is calling itself to many times.
Don't call your code that many times
its happening on line 125 whenever you process an answer. What lines 121-125 are essentially doing right now is the following: ```
121: Creates a function called checkinput
122: Wait for a message event and assign it to an object 'antwort'
123-124: Check conditions
125: If conditions met, call checkinput and start at 122 again
waht do I do?(
Someone pls 😂
I think either your function names are being overwritten or your indentation is screwy
Oh okok
that was directed at @slate swan i apologize
I didnt see anything
Can anyone pop up docs for wait_gor
!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.10)"). 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.10)") 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.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
@slate swan you are calling a function from inside itself, this causes an infinite loop
you need to restructure your code a bit to prevent that
@slate swan read this and use check argument instead of the if clause and recursing function afterwards and
thats not the error you have. you need to fix the recursion first
Nested function 😔
most of them
Read the docs for wait_for and you will see that u can completely avoid recursion
something like this to get you started @slate swan ```py
async def check_input(message: discord.Message) -> bool:
Conditional statements, return either True for valid response or False for invalid response
answer = await bot.wait_for('message', check=check_input)
Continue processing answer value
notice I placed the two lines on the same indentation level, meaning the wait_for is not called inside of the check_input function, which will prevent the infinite recursion error
^
What u did is completely different from this
Pls read this
okay, so you are stilling calling it from inside itself.
Your code has to change more than one line
U messed it up because you don’t understand how to use the method because you refuse to read the docs
you have to rethink your approach and I provided a hint to get you on a good path for doing so
your check_input function is going to just do logic for you. like a filter. outside of that is where the rest of your code is.
anyone?
segregation is really useful in your code in moderation. There is a point where it becomes too much, but a little never hurts.
It helps keep your code clean, organized and easy to read, which in turns allows people to assist you more easily, makes it easier to find errors and troubleshoot. If you have 30 things going on in one function, there could be 30 things wrong. 3-4 or even 7-8 things in one function makes it super easy to pinpoint issues.
Pop up the docs for copy_global_to
!d discord.app_commands.CommandTree.copy_global_to
copy_global_to(*, guild)```
Copies all global commands to the specified guild.
This method is mainly available for development purposes, as it allows you to copy your global commands over to a testing guild easily.
Note that this method will *override* pre-existing guild commands that would conflict.
iirc a couple days ago you were asking for help with a project that violated Discord ToS, so while I would love to help you - I am going to refrain from doing so as to not further assist you in your endeavor
what???
discord.Object only has an id, you need a discord.Guild object
what;s the full exception?
aight, ig I'd better put it here: https://hastebin.com/ogebefewol.sql
the method takes a snowflake, which is anything with an id attribute
Nvm I read the whole question wrong
seems like the bot is not logged in yet, so it does not have an application ID, try syncing in an on_ready or something ( just to test ) to see if that helps
Could you then please say what did I try to do, that violates ToS, because if I actually did, I will remove it. I didn't mean to break ToS and don't want to, I'm completely against it
ok
yep and if thats not the case, somethings wrong with your commandtree, you might have some incomplete commands like an empty describe or something
Now it does not say anything (just literally nothing in terminal)
async def on_ready(self):
# Hybrid commands set up
self.tree.copy_global_to(guild=discord.Object(id=980346257371455528))
await self.tree.sync()
print(f'{self.user} is ready. Loaded {", ".join(self.loaded_extensions)}')```
not even the print?
hm check your app commands.then
wdym?
wait, empty describe... I guess in like 3 minutes I'm gonna say I'm super dumb
Yeah I'm dumb, I did not provide description for one option in describe
It was sooo long tho, I already thought it won't print anything as last time.
But there's still a problem @slate swan I added self.tree.copy_global_to(guild=discord.Object(id=980346257371455528)), so slash commands would work only on test server, but they also work on second server where my bot is, I thought they'll be removed from it automatically, or that doesn't work like that?
~~ sublime is probably even worse~~
Ofc, I have no idea why people even use it as code editor. They say "plugins". What's the fricking purpose of plugins for literal text editor when you can use a normal IDE
Anyway this is not #editors-ides
I was using it only because I only new about it, when I heard about vsc I was like hjdsgfjashd what is this? why's it so good?
Send ss of full code
Just google, try and see
It aint, It’ s Microsoft
Redefinition of builtin 😩
Whats that else doing there?
Name it obj man why'd you redefine internal class
object is builtin
The class from what everything inherits
Rename it to obj
But that aint the major issue
U dont know?
Yes
😂 It’ s floating there without an if
hey guys, im wondering how i can send a message to a user when they join my server via my bot, tried searching all over he place and i still have no idea how to send a message to the user when they join
!d discord.on_member_join
discord.on_member_join(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") joins a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
instead of using if-else statements, you can just use the @commands.has_role check decorator
@commands.has_permissions
Yes but there are multiple ways to fix it, the most simple one would be to deleta all the code but thats not what ur trying to do
I would suggest reading through the documentation a bit to get a feel for what you can do. Its a great reference material
when i started using d.py like 6 years ago I was infuriated at the number of people that told me to "rtfd" - but I can honestly tell you it was the best thing for me to do. It helped me seriously improve the quality of my code more than school or tutorials ever did
U should probably read python docs first
isn't that just a port of d.py
it should have the same basic functionality, maybe called something else
It’ s helpful to learn python syntax and oop and bit of asynchronous programming before making bots
can you use client.event to send a message to a member?
Wdym
How are u picking winners
its better to send your code in codeblocks or use the pastbin service
ik u can use a command to send it but idk about an event
I kinda like screenshots
you can send message to members inside an event, but you can't literally use @client.event to send message to members
You can send a message to user when event is triggered
i just want a welcome message for my members when they join through dms
Use on_member_join listener
!d discord.on_member_join
discord.on_member_join(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") joins a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
Click on this and read the docs for it
@slate swanctx is shorthand for context which is whatever context a command is invoked with.
an event usually has very specific arguments and values passed to it, for instance on_message gets passed a discord.Message object.
Likewise, a on_member_join event gets passed a discord.Member object.
so to answer your question, yes you can send a message inside of an event function, but how you go about doing so varies depending on the event you put it under
Whats users?
what would the point of a try/except if you just pass over the error.
If you are having trouble with something, it might be better to raise the error to better figure out where things are breaking
we aren't going to hand you every solution to every problem you encounter. That will not help you at all. We are here to give you hints and point you in the direction of a solution so that you can arrive there on your own and retain the pathway. The only thing learnt from spoonfeeding is a dependence on others to do everything for you.
I said it might be better to raise your errors to pinpoint where your code was breaking, and I also said that the try/except is just passing over the error. Can you try to figure out what you might need to do from that?
how to make a bot using python can anyone help, I am a beginner.
discord.py and relative forks are not beginner friendly
they don't get removed automatically, you can remove the using bot's http methods or raw requests
pin any resources to learn about making a bot for a beginner
start with this https://www.guru99.com/python-tutorials.html
learn python basics, OOP and a bit of asynchronous programming
i keep getting this error "discord.ext.commands.errors.CommandNotFound: Command "ban" is not found"
I get it whenever i try the: clear , ban , kick command
I know python but i want to know a platform where i can start to make a bot
me too
could be a lot of different things, I would start by checking your code to make sure function names and aliases are matching what you are trying to use. If the commands are in a cog file, I would make sure the cog is being loaded properly.
There isn't any plaltform where you can learn d.py or any other forks from what i know
There is just the documentation and the example on github, that's all you need
is d.py a discord bot?

🥲
😂
d.py (discord.py) is the API wrapper for the discord API
heheh, see i am compltely new.
but now I have all the basis of python covered, now I wanna make some real stuff.. something of use
bruh i don't develop in js
hi all , A quick newbie question
this is python server 💀
this is the python server mate, and on top of that this is for discord.py related questions. We don't answer js questions
i can't help you, and this channel is for discord bot in python 
😅 ok
so to make a Bot I have to first go through Gurru99 ?
no, thats just a link for a tutorial
What is gurru99?
to make a bot you need to know Python basics, asynchronous programming, OOP concepts and how to read a documentation
no one knows last
a quick rundown of python basics. There is a getting started guide on the discord.py rtd once you get going
I already know 70-80% of tutorial there on guru99, so what's the next step after this , if I intend to make a bot
see? Filet does 
Gotcha
Well, I also do, that was like a joke...

Filet did not answer my question. Which means he... uhm no... im too garbage at jokes
I would like to appreciate everyone here. I have been on discord its been like just 2-3 days and guys here are awesome and very helpful
Anyone know if you can add indents in webhook embeds?
\n
not through python
uhm so wdym?
try with an invisible character
ah it works with them
sorry for the late response but I just had to add something -
I started my python career in the d.py server. Anytime you asked a question there, you got the same answer rtfd. It was such a popular response that they actually had a tag for it and just blanketed it on every help channel. I learned really quick to think for myself and work through my own problems. To analyze what I was doing and why I was doing it. Formulating routes to get me from point A to point B.
When I got to this server I vowed to try my absolute hardest to teach people the methods I acquired through learning on my own, while not discouraging them with a simple rtfd which had been done to me so many times. It tends to work pretty well but every once in a while you get someone that doesn't want to spend 2-3 minutes looking at documentation to understand why its not working or how to make it work.
Guys any command idea for my bot?
If I could tell anyone starting out programming or with discord.py or anything, it wouldn't be learn python basics first, or any of your typical answers. I would simply help them learn to think like a programmer. Once you have that skill, everything else falls into place. You learn how to learn and how to apply the knowledge you learn to your code, anything you want to do after that is just building on that foundation
(my apologies for the rant - tl;dr trauma + persistence + brain = good stuff)
interesting
/nerdify
If they aren't ready to take the effort to learn python basics and read documentation, what makes you think they're going to be ready to learn how to think like a programmer 🙂
im glad i've learnt all this (except rtfm) from my dad (idk how but when I just saw docs I started to read them...)
Whats purpose of this command?
I learned python thrice
my favorite thing to make in discord has always been a leveling system. Not really so much a command but a network of commands. Built one for a popular youtuber once that used an AI based entirely on Harry Potter novels and the Lord of the rings to grade messages and reward varying amounts of xp based on that grade
It turns you into nerd 🤓
Whats nerd?
mine is economy
two sides of the same potato really
economy has work :lemao:
does pycord/discord.py send newlines?
context.respond("y\nNewline")
should be
y
Newline
``` or
y\nNewline
just a quick question
Cant afford to test it atm
at least for me
How does it utilize AI
yes
itworks
which one
1
alr thanks
I had it read random sentences from all the books and analyze different characteristics like vowel count, character/word frequency, word/character count, how many diffrerent subjects there were, predicates and prepositions and all sorts of stuff to train it. Then it would examine a message and evaluate it against the baseline values from the novels and the grade was an 100% - the variances for each characteristic
Interesting
it also doubled as a surprisingly good spam filter 🙂
used the same logic later on in a email program
I have one bot with AI the purpose of which is the antispam lol
AI is pretty sweet once you get the hang of it
What method of text vectorization did you use if you have
can i use nextcord.channel for slash commands in nextcord??
if not what can i use for getting channels in slash commands nextcord??
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.
no not that
Then what exactly do you mean
When embed not in cache lol
Permissions v2 or smth
I think I used a combination of transfer learning and tf-idf
Ah just typehint the argument with nextcord.TextChannel
ok..
Tf-idf is the best method imho lol
That's pretty cool
thanks 🙂
In my antispam bot I use unique characters/words amount with total amount of characters and words and it works fine
I like to go overboard
Guys im getting an unknown interaction error for a slash command im using in nextcord and this shit got me confused as hell
Recently I tried text generation with tensorflow but it smoke grass with saving the model and I don't have nvidia GPU so it takes a while
Leveling for what specifically?
Oh messages
You will need a database with table with scores and table with levels
the basic concept is pretty much just ```
1: Receive Message
2: Get Author of Message
3: Create/Add XP to Record of Author in Database
4: Command to Query Database and see XP for user
^ That is extremely oversimplified, but a good starting point to help you visualize what needs to happen
Oh y'all doing messages a lot different from how I'd approach it
what kind of error? not familiar with nextcord but I might be able to help nonetheless
4: Check if user has enough to level up
5: If yes, give them next level
what's your code?
I'll send what the beginning and ends of it look like
Don't mind the ctx: Interaction field btw
I moved from discord py a while back and I didn't feel like changing the variable to interaction
Send how you define the slash command that causes that error, like
@bot.slash_command(name="yes")
async def _yes(ctx, *args):```
@client.slash_command(name="rostercheck", description="Provides a roster report for every registered franchise", guild_ids=devGuildid)
async def rostercheck(ctx: Interaction):
Ik
I can do this all but problem is with the cooldown
hm, what line raises an error? or just send full traceback
The error triggers where I try sending a embed I created
what is the problem?
Just have a dict with user ids as keys and datetimes as values
Btw the embed is fine before u ask, becuase i wasnt given an "invalid fields" or whatever it's called
can you please send full traceback or line where the error appears?
maybe keep a dictionary of {userID: time of last xp reward} to start with
I'm getting it rn
no, CooldownMapping exists
get bucket, store in Counter
Pretty sure internally it is still a dict lol
await ctx.response.send_message(embed=embedyes)```
well.... it's better)
I'll show the embed as well
I want like on typed message and he got 5 exp so i want he gets 5 seconds cooldown and then if he send message he gets 5 exp
Just higher level implementation of the same thing functionally isn't always better but I am not arguing as I never saw its source
I see
embedyes = nextcord.Embed(
title="Franchise Ownership Report")
embedyes.add_field(name="Claimed Franchises", value=normteams2)
embedyes.add_field(name="Open Franchises", value=freeteams2)
embedyes.add_field(name="Abandoned Franchises", value="[WIP]")
embedyes.set_footer(text="Abandoned Franchises just means teams that HAVE MEMBERS on them but without an FO")
await ctx.response.send_message(embed=embedyes)```
All the variables were checked and doesn't invalidate the embed
bruh my nextcord docs aren't loading
There isn't much different from nextcord and discord
Most of the stuff is the same
Just changed name
hmm, seems valid, idk
Me neither 🤷🤷🤷🤷
How would i do it?
Everything was going smoothly and now I'm getting some "unkown interaction" bullshit like what??
It's literally under the same async def function
And everything else with it
Wait holdon I might know
@silk fulcrum are you experienced with how slash commands work?
If you are Is there like time limit before slash commands are immediately invalid after imitating the command?
So, if you are using a cog, that'd be easier cause you can define something like self.lvling_cooldown in __init__ method, but im not sure where is it better to put lvling_cooldown if you are not using cogs. So what you do is you define lvling_cooldown = commands.CooldownMapping.from_cooldown(1, 5, commands.BucketType.user) (1 is messages and 5 is seconds of cooldown) and in on_message you get message bucket like this bucket = lvling_cooldown.get_bucket(message), then you check if there is a rate limit, like this if bucket.update_rate_limit(message.created_at) and if yes, then the user is on cooldown and you do not give him anything
I thought about Counter, because I used it to count user's messages and autoblock if they're spamming
but here Counter is not required
hm... probably
That still uses a dict (confirmed) https://github.com/Rapptz/discord.py/blob/master/discord/ext/commands/cooldowns.py#L95
discord/ext/commands/cooldowns.py line 95
self._cache: Dict[Any, Cooldown] = {}```
Because I have a feeling that's what might be happening
Except as values they use some custom class
I used asyncio throughout the code a couple times
Imma try sleeping the code for 100 seconds
And see if it invalidates early
Who cares, it's already done and most likely faster then something you will create yourself and also it looks good)
To your preference
@silk fulcrum yeah there's defintly a time limit on it 😂
ok
But as for "faster" I could argue
I mean I guess it makes sense
But like I did it to prevent api bans
So it sucks that slashcommands do that
Don't underestimate my nanoseconds obsession 😈
When i try to ban someone it gives me this error
"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: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions"
1 of these:
- your bot does not have permissions to ban members
- member that you are trying to ban has a role that's higher in hierarchy than bot's role
- this member is admin or owner of the server
how to use a varibale from an if condition to another one ?
@silk fulcrum can you help please ?
w what?
wdym use variable from an if condition?
if ........ :
elif (and i want to use a variable from the if) :
is it possible ?
but what is variable from the if
variable cannot be defined in if
well, technically it can.. by if var := something
but are you really using that?
no a varibale into the if
I don't get you
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
uwu
yeah
you dont even need the parens here
she has used too much javascript
Literally any language that uses braces for if conditions
yup but lil ash use javascript 
its like use the tokens generated from a random system to create accounts to login for a special perks
!d secrets.token_urlsafe
secrets.token_urlsafe([nbytes=None])```
Return a random URL-safe text string, containing *nbytes* random bytes. The text is Base64 encoded, so on average each byte results in approximately 1.3 characters. If *nbytes* is `None` or not supplied, a reasonable default is used.
```py
>>> token_urlsafe(16)
'Drmhze6EPcv0fN_81Bj-nA'
this is for generating tokens
warning sys, verification sys
ok so how about signing up an account with that token
you want user to log in using their token? not password?
hol up how can i use token_urlsafe in discord python
!e ```py
import secrets
print(secrets.token_urlsafe(20))```
@silk fulcrum :white_check_mark: Your 3.11 eval job has completed with return code 0.
IyNXdDvm_uevQUheIkXNX1mCv-M
understand
how can i use missingrole command error
SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers
test1 = sp.getoutput("command output")
result = test1 + teet2 + test3
embed = ... {eval(result)} ..
Why? Is this error
This error happens when you put leading zero in decimal
!e py num = 07 print(num)
@silk fulcrum :x: Your 3.11 eval job has completed with return code 1.
001 | File "<string>", line 1
002 | num = 07
003 | ^
004 | SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers
How can i fix?
do not put zero there
!e py print(0o67)
@vale wing :white_check_mark: Your 3.11 eval job has completed with return code 0.
55
Sus
Are you trying to do math command
Traceback (most recent call last):
File "c:\Users\ADMIN\Desktop\bot discord\cat.py", line 213, in <module>
@bot.event()
TypeError: Client.event() missing 1 required positional argument: 'coro'
whats this
No braces for @bot.event
why so fast(
No
I sum
Output of command u can see in sp.output
why my commands don't want to run , but my events run !
@bot.event()
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingRole(1006214471909380257)):
await ctx.send("error")
wdym no braces i thought i put it
just remove () from @bot.event
that's how it works
oh ok
when i dont have the required roles it say this
Traceback (most recent call last):
File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "c:\Users\ADMIN\Desktop\bot discord\cat.py", line 215, in on_command_error
if isinstance(error, commands.MissingRole(1006214471909380257)):
TypeError: isinstance() arg 2 must be a type, a tuple of types, or a union
you cannot use MissingRole as a method, it's an exception, so just commands.MissingRole
oh ok
@bot.event
async def on_command_error(ctx):
if isinstance(commands.MissingRole(1006214471909380257)):
await ctx.send("error")
so its only this?
no
I did not mean that you have to remove error
you compare it, so that was right
understand
Method is function for class so I meant that you can't use (), and even more pass something in them
it should be just commands.MissingRole
without brackets and id
ty
how can i get req.txt in python ?
@bot.event
async def on_command_error(ctx, error):
if isinstance(commands.MissingRole):
await ctx.send("error")
Traceback (most recent call last):
File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "c:\Users\ADMIN\Desktop\bot discord\cat.py", line 215, in on_command_error
if isinstance(commands.MissingRole):
TypeError: isinstance expected 2 arguments, got 1
what 😭
hey uhm what's the color code for blending in the sides of embeds
!d isinstance
isinstance(object, classinfo)```
Return `True` if the *object* argument is an instance of the *classinfo* argument, or of a (direct, indirect, or [virtual](https://docs.python.org/3/glossary.html#term-abstract-base-class)) subclass thereof. If *object* is not an object of the given type, the function always returns `False`. If *classinfo* is a tuple of type objects (or recursively, other such tuples) or a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union) of multiple types, return `True` if *object* is an instance of any of the types. If *classinfo* is not a type or tuple of types and such tuples, a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") exception is raised.
Changed in version 3.10: *classinfo* can be a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union).
@silk fulcrum can u help me?
you need to pass error
pass it in isinstance()
@bot.event
async def on_command_error(ctx, error):
pass
Like this
what is this
hey uhm what's the color code for blending in the sides of embeds
To pass error
I don't know how, I said to not use 0 at the start of decimal, that's what error says
I say for @short relic
no that's not what should happen
!d discord.Embed.color
!d discord.Embed
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
x == y Checks if two embeds are equal.
New in version 2.0...
there is color arg
there is a color code that is the same as the embed that blends it in but im not sure what it is
@bot.event
async def on_command_error(ctx, error):
pass
if isinstance(commands.MissingRole):
await ctx.send("error")
u mean this///
like this
0x36393F if im not mistaking
that worked, thanks
color=discord.Colour.dark_theme()
It would be something like this
yep ty
is Reply considered as message ?
yes
in dpy reply information is inside message.reference
hm why not
No clue but I remember having issues with that thing too
well this is reply to message
I meant the slash command invoke, my bad english
but we can't really help you without code
ok wait
how to make eval command
This thing doesn't get caught in on_message?
Owner only or for everyone
ownrr
it's longer that i can send
💀 !src
!e
pp
@slate swan :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'pp' is not defined
If you don't need async support you can just use eval, if you do need it then tell me
a command like that
your on_message code contains more than 2000 symbols?
yep 🙂
how
!paste well anyways this exists
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.
yep
One sec ima give you the example
!paste
how hh
!e py eval('print(\'yes\')')
@silk fulcrum :white_check_mark: Your 3.11 eval job has completed with return code 0.
yes
read bot's message
oh
A sample exec command with async support
nameWithIt =(message.content.split("| "))[1]
NameOfTransferrer = (nameWithIt.split(" has"))[0]
TheName = NameOfTransferrer.rstrip(NameOfTransferrer[-1])
Amount = (message.content.split("$"))[1]
Quantity = (Amount.split("` to"))[0]
print (TheName)
if message.author.id == 282859044593598464 and message.content.startswith("**:moneybag:") == True and message.content.endswith("@IBRO,Niva#6356**") == True :
await message.channel.send ("**"+NameOfTransferrer+" send me a 'done' message in the dm**")
data.remove(Tra.name == TheName)
data.insert({'name':TheName,'isTransferrer':"Yes",'quantity':Quantity})
except :
try :
dictio = (data.search(Tra.name == message.author.name))[0]
BoolTra = dictio.get("isTransferrer")
Dicttt = (data.search(Tra.name == message.author.name))[0]
IntQua = int(Dicttt.get('quantity'))
AmountToGet = int(IntQua/1000)
except :
data.insert({'name':message.author.name,'isTransferrer':"No", 'quantity':0})
if message.content == "done" and BoolTra == "Yes":
try:
dicofmem=(db.search(Mem.name==message.author.name))[0]
newww = dicofmem.get('balance')
newbalance = int(newww) + int(AmountToGet)
db.remove(Mem.name == message.author.name)
time.sleep(0.1)
db.insert ({'name':message.author.name, 'balance':newbalance})
data.remove (Tra.name == message.author.name)
data.insert({'name':message.author.name, 'isTransferrer':"No",'quantity':0})
await message.reply (content="**You transferred "+str(IntQua)+" credits, you got `"+str(AmountToGet)+"$`**")```
@silk fulcrum i deleted the not important things on the code
Bro use listeners and split it into several functions, pretty sure you are just doing a lot of stuff linearly
can you explain more , because i don't understand english much
Oh damn looking at this code I see so many bad things but no worries ima tell you about them
You can use translator
i used
ok thanks
but really it works
tha only thing that doesn't work is on reply
- There are naming conventions you are not following at all. Google PEP 8 and see, or use some smart IDE with linting to find them "interactively"
- Don't use
time.sleepin async functions, useawait asyncio.sleep - Instead of doing lots of concatenation, just use f-strings
!f-strings
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
This is just some
is there an simpler one-
What is db.remove(smth == smth), you are basically removing a boolean
Only with no async support
in the course that i seen , they used + in variables addition, without this f and {}
2- ok
does it work without async support
Yeah
tell me hhow
Just use exec()
plezx
Or eval
how to send the result and err
That's only possible with eval (or with my implementation)
you can see danny's implementation https://github.com/Rapptz/RoboDanny/blob/rewrite/cogs/admin.py#L214-L259
Mine is shorter 😀
okay well thats just for reference
mines much longer but handles output in different ways
Do yall think its bad coding on a mobile device?
me yes
im getting a new laptop soon but i don't wanna stop coding rn
i host bots on mobile anyways :)
What laptop should i get ? Anyone have recomendations?
how can i make it so that if they use the command =redeem(code) then they will have some perks
wdym perks
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
to give special roles
wait but can i do
@bot.commands()
async def redeem(ctx, code):
if code.content == "":
ctx.author.add_roles(...)
you'd generate some code for them and this to add roles to them <#discord-bots message>
why code.content
just code
I have !clear command but for some reason i get rate limited due to this command. Does someone know why this happens?
show ur code
sum() takes at most 2 arguments (7 given)
how can i sum more then 2 args
!d sum sum takes an iterable not different arguments
sum(iterable, /, start=0)```
Sums *start* and the items of an *iterable* from left to right and returns the total. The *iterable*’s items are normally numbers, and the start value is not allowed to be a string.
For some use cases, there are good alternatives to [`sum()`](https://docs.python.org/3/library/functions.html#sum "sum"). The preferred, fast way to concatenate a sequence of strings is by calling `''.join(sequence)`. To add floating point values with extended precision, see [`math.fsum()`](https://docs.python.org/3/library/math.html#math.fsum "math.fsum"). To concatenate a series of iterables, consider using [`itertools.chain()`](https://docs.python.org/3/library/itertools.html#itertools.chain "itertools.chain").
Changed in version 3.8: The *start* parameter can be specified as a keyword argument.
!e
print(sum((1, 2, 3, 4,)))```
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
10
How do I get all roles name the user is having?
description=ctx.author.roles
Or how do I separate the roles in new line?
the names?
List comprehension
with the join method of the str object
@bot.command()
async def redeem(ctx, code):
if code == "deptrainhatsv":
await ctx.send("key successfully redeemed")
await ctx.author.add_roles(1006216298562326588)
else:
await ctx.send("key not found")
why is it not adding role
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
why no typehint, anyways
I believe you need to pass in discord.Role objects, not ids
yes
how do i do that...
No documentation found for the requested symbol.
!d discord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
Changed in version 2.0: `role_id` parameter is now positional-only.
With this
@bot.command()
async def redeem(ctx, code):
if code == "deptrainhatsv":
guild = bot.fetch_guild(id)
role = guild.get_role(id)
await ctx.send("key successfully redeemed")
await ctx.author.add_roles(role)
else:
await ctx.send("key not found")
can i do like this
how 💀*
Traceback (most recent call last):
File "/home/runner/Astro/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/Astro/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/runner/Astro/venv/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: 'Embed' object has no attribute 'set'
i have this error the code is:
@bot.command(aliases=['Avatar'])
async def avatar(ctx, *, member: discord.Member=None):
member = ctx.author if not member else member
embed = discord.Embed(title=member.name + "#" + member.discriminator)
embed.set.image(url=member.avatar_url)
await ctx.send(embed=embed)
pls help?
Did u test it?
set_image
!d discord.Embed.set_image
set_image(*, url)```
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
ohk
ok
thanks
just use ctx.guild
ctx.guild.get_role
you can do that too ?
yes
description="\n".join([role.name for role in member.roles])
i have version 3.7 / how can i update it on linux ?
in my aws instance
@bot.command()
async def redeem(ctx, code):
if code == "deptrainhatsv":
role = ctx.guild.get_role(1006216298562326588)
await ctx.send("key successfully redeemed")
await ctx.author.add_roles(role)
else:
await ctx.send("key not found")
didint work 💀
error?
I mean it's probably just that that you're the owner of the server and the bot can't add roles to you
im no the owner tho
and no error
didnt work 💀


