#discord-bots
1 messages · Page 131 of 1
count = View()
count = count.remove_item(count)
count = count.add_item(select)
await ctx.send("test menus", view=count)
someone pls help me remove the button
after saving the user OAuth2 token for a user after allowing me to use guilds.join how can i make the user join back to the guild?
when a ticket is opened via ticket tool i want my bot to copy the id i send so i can add the person to the ticket, this is how far i came anything i can fix? because it wont run
how can do something like this in my phynton program, when a task finishs:
- succes
- succes
!d discord.ext.tasks.Loop.after_loop
@after_loop```
A decorator that registers a coroutine to be called after the loop finishes running.
The coroutine must take no arguments (except `self` in a class context).
Note
This coroutine is called even during cancellation. If it is desirable to tell apart whether something was cancelled or not, check to see whether [`is_being_cancelled()`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop.is_being_cancelled "discord.ext.tasks.Loop.is_being_cancelled") is `True` or not.
anyone know if the command invocation can be stopped in before_invoke
Hey I need some help, as I don't know what to do for using python to insert data into SQL db
most stuff I find is from years ago, and their code doesnt work anymore
ask in #databases for db-related help I guess
I love the guy in your pfp
Aladdin has always been my idol
!d discord.ui.Button
class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.
New in version 2.0.
whats the best library to make discord bots with?
user preference tbh. some allow more control. Just do your research
alright, I was using discord.py for a bit but saw that it was discontinued so I was looking for another one
it’s back to being maintained
That is old news
oh alr
you're not the first to have mistaken dpy for having been discontinued, but i would have thought itd be pretty well known after several months
dpy v2.1 actually came out today as well
oh thats cool
it doesnt help that if you google discord.py the first result says it stopped being updated
hm it just shows the dpy docs for me
yeah almost everything does
I was searching up how to do slash commands with it
and it said it doesn't support it and never will because it got discontinued
if you're interested in whats changed, they have a migration guide and changelog you can look through
https://discordpy.readthedocs.io/en/stable/migrating.html
https://discordpy.readthedocs.io/en/stable/whats_new.html
or if you still want an alternative you can look at disnake, nextcord, or hikari
I was looking at interactions earlier
i have a problem with my giveaway bot. i have it set to add the members who reacted to the giveaway to a list, and based on your roles you can have additional entries by adding your name to said list multiple times. however, when i pull random.sample() from the list of entries, it still gives duplicates even though sample isnt supposed to give duplicates
How would I make slash commands with it though lol
does the list you're sampling from have duplicates? if so, sample can pull multiple elements which are the same user
you can see an example bot on the github
https://github.com/Rapptz/discord.py/blob/master/examples/app_commands/basic.py
thats the problem im having, in order to give users with specific roles more entries im adding them to the list multiple times
which results in multiple of the same winner when i want more than one winner
maybe ill have to make a new list from the first list by grabbing a random element and if it already exists in the second list, try again?
just seems like a lot of shenanigans to not get duplicates with my sample
huh, random.sample doesnt support specifying weights for each element
yea all it does is which list youre sampling and how many to pull afaik
random.sample then cast to set to remove duplicates
now full circle, is why i weighted the list with duplicates lol
then my sample will be smaller than intended
if choice.value == 1:
with open("users.json", "r") as f:
users = json.load(f)
await reset_money(users, interaction.user, member)
with open("users.json", "w") as f:
f.dump(users, f)
reset = discord.Embed(title=f'Reset {member}', description=f"{member}'s Money has been set to 0!")
await interaction.response.send_message(embed=reset, ephemeral=True)
why is this resetting my json file?
Your sample is still the same size but all the duplicates are removed, unless you mean some edge cases where the only winner is a single user?
if i want 5 winners, pull a sample of 5, then remove the 2 duplicates im left with 3 total instead of 5
async def reset_money(users, user, member):
users[f'{member.id}']['money'] = 0
Check length of the set after removing duplicates then push more if the size isn't right
You could call sample again with the delta size or whatever
hmmm ill give that a try
dump() isnt a method of f, which would have caused an error and resulted in your file being erased
many have suffered from the mistakes of one youtube guide
LOL
!e ```py
from random import choices
entries: dict[int, int] = {}
for i in range(10):
entries[i] = i*2 # pseudo entry
print(entries)
def select() -> list[int]:
return choices(list(entries.keys()), weights=list(entries.values()), k=5)
print(select())
@mighty pilot cc
Keep in mind you still need to filter for duplicates
@pliant gulch :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | {0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18}
002 | [5, 4, 9, 7, 3]
!e
code
!eval [python_version] <code, ...>
Can also use: e
Run Python code and get the results.
This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.
If multiple codeblocks are in a message, all of them will be joined and evaluated, ignoring the text outside of them.
By default your code is run on Python's 3.11 beta release, to assist with testing. If you run into issues related to this Python version, you can request the bot to use Python 3.10 by specifying the python_version arg and setting it to 3.10.
We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!
!e
print('e")
@slate swan :x: Your 3.11 eval job has completed with return code 1.
001 | File "<string>", line 1
002 | print('e")
003 | ^
004 | SyntaxError: unterminated string literal (detected at line 1)
!e
print('hey')
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
hey
i didnt watch a yt vid
with open('inv.json', 'w') as f:
json.dump(users, f)
A little bit more complicated than how I have it setup lol
It's a lot better than what you had though
You're method was a lot more memory intensive becuse it requires duplicated entries in the list
Well I have it working just need to filter duplicates
whereas you can get a minimal footprint with a dictionary
I'm not worried about memory I have a rack server in my house
and this is the only bot currently running on this VM
but there is one particular youtube video about creating an economy bot that uses json in the same way that you do, and that others have copied while they followed along
kek ¯_(ツ)_/¯
i use to watch those lol but since i got a level system from stack over flow ive made(and still working on heavy) my 1800 line bot for economy and moderation.
Point being: I think I'm just gonna use what I have and filter for duplicates since it's already set to add users to the list multiple times for various roles and it already prints the users who entered without duplicates etc
can you help me with my json errors?
I need help with making something global
json errors arent really related here, id ask in a help channel
If you want something to be global just don't specify a guild
in general, repeatedly writing data to just a bare file has a higher risk of corruption than a database
inb4 writing 1000 new entries to your JSON file and there is a power outage

Good thing I remembered to use rync instead of mv in my arch install when I was moving home mounts
Reminds me of that
async def add_word(guilds, guild):
word = client.word
word2 = f"'{word}', "
guilds[f'{guild.id}']['words'] + word2
@client.command()
async def test1(ctx, word):
with open("serverconfigs.json") as f:
guilds = json.load(f)
client.word = word
await add_word(guilds, ctx.guild)
with open("serverconfigs.json") as f:
json.dump(guilds, f)
client.word = ''
Traceback (most recent call last):
File "/home/runner/game-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 190, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 1825, in test1
json.dump(guilds, f)
File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/json/__init__.py", line 180, in dump
fp.write(chunk)
io.UnsupportedOperation: not writable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/game-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1347, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/game-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 986, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/home/runner/game-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 199, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: UnsupportedOperation: not writable
You need to open the file pointer with "w" to make it write-able
Also does add_word really need to be a coroutine function? Everything inside of that coroutine function is atomic
Trying to make a simple application command and the embed is not being sent to the channel. Been a while in discord.py
@bot.command()
async def app(ctx):
await ctx.author.send("Discord Username ")
DiscordUser = await bot.wait_for('message')
await ctx.author.send("Age ")
Age = await bot.wait_for('message')
await ctx.author.send("Timezone ")
Timezone = await bot.wait_for('message')
await ctx.author.send("How long can you moderate per day? ")
ModerationTime = await bot.wait_for('message')
await ctx.author.send("Any Experience: ")
Exp = await bot.wait_for('message')
await ctx.author.send("Why do you want to become a staff member? ")
WhyStaff = await bot.wait_for('message')
await ctx.author.send("Key Positions of being Staff? ")
KeyPositions = await bot.wait_for('message')
await ctx.author.send("How can help the server? ")
HelpServer = await bot.wait_for('message')
await ctx.author.send("Situation: A mod has commented on your moderating capabilities, what do you do?")
Sit1 = await bot.wait_for('message')
await ctx.author.send("Situation: If you fail this application, what would you do")
Sit2 = await bot.wait_for('message')
await ctx.author.send("Situation: A person has tried to use bots in general, what do you do?")
Sit3 = await bot.wait_for('message')
await ctx.author.send("Situation: A moderator or an admin is abusing their perms, what do you do?")
Sit4 = await bot.wait_for('message')
await ctx.author.send("What role are you applying for?")
RoleApplying = await bot.wait_for('message')
await ctx.author.send("Application Submitted! Your application is being processed and may take a few days so please be patient!")
appChannel = await ctx.get_channel(1041124949361963089)
appEmbed = nextcord.Embed(title=f"Application From {ctx.author}", color=nextcord.Color.random())
appEmbed.add_field(name="Discord Username", value=f"{DiscordUser.content}")
appEmbed.add_field(name="Age", value=f"{Age.content}")
appEmbed.add_field(name="Timezone", value=Timezone.content)
appEmbed.add_field(name="Moderation Time", value=f"{ModerationTime.content}")
appEmbed.add_field(name="Experience", value=Exp.content)
appEmbed.add_field(name="Why do you want to become staff", value=f"{WhyStaff}")
appEmbed.add_field(name="Key Position of Staff", value=f"{KeyPositions.content}")
appEmbed.add_field(name="How can you help the server?", value=f"{HelpServer.content}")
appEmbed.add_field(name="Situation: A mod has commented on your moderating capabilities, what do you do?", value=f"{Sit1.content}")
appEmbed.add_field(name="Situation: If you fail this application, what would you do", value=f"{Sit2.content}")
appEmbed.add_field(name="Situation: A person has tried to use bots in general, what do you do?", value=f"{Sit3.content}")
appEmbed.add_field(name="Situation: A moderator or an admin is abusing their perms, what do you do?", value=f"{Sit4.content}")
appEmbed.add_field(name="Applying for Role", value=f"{RoleApplying.content}")
await appChannel.channel.send(appEmbed=appEmbed)
yeah it should be client or bot
@client.command()
async def test1(ctx, word):
with open("serverconfigs.json", "r") as f:
guilds = json.load(f)
client.word = word
await add_word(guilds, ctx.guild)
with open("serverconfigs.json", "w") as f:
json.dump(guilds, f)
now this isnt writing in the file
async def add_word(guilds, guild):
word = client.word
word2 = f"'{word}', "
guilds[f'{guild.id}']['words'] + word2
well know I got it to work
{
"cursewords": [
"curse1",
"curse2",
"curse3",
"curse4",
"curse5"
]
}
how can I get my json like this
{"1041109270931972096": {"words": "'hi', 'bell', "}
its like this
why are you defining client.word when you could just pass the word to the function
i have no idea
not rlly
def save_stats(stats):
with open('stats.json', 'w') as f:
json.dump(stats, f, indent=4))
if authorid {'bye'} in log_data:
log_data[str(message.author.id)]['bye'] += 1
save_stats(log_data)
!e
my_data = {
"jeff": [
1,
2,
3
]
}
# add a key to this dictionary
my_data["bob"] = [2, 3, 4]
# access a key in a dictionary and add an item to a list
my_data["jeff"].append(420)
# printing to show you the new dictionary
print(my_data)
@dull terrace :white_check_mark: Your 3.11 eval job has completed with return code 0.
{'jeff': [1, 2, 3, 420], 'bob': [2, 3, 4]}
how could i disable ban_members permission on a role via bot
still confused
dictionary = {"key": "value"}
list = ["a", "list", "of", "things"]
!e
dictionary = {"bob": 1}
#accessing a dictionary
print(dictionary["bob"])
lst = ["index 0", "index 1"]
#accessing a list
print(lst[0])
@dull terrace :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 1
002 | index 0
so if you use commands.Bot() it already comes with a tree, right
if so, how would I access the decorator @tree.error
@bot.tree.error
bot being an instance of commands.Bot
u know im kinda dumb
@client.command()
async def logoutt(ctx):
if message.author.id == 625899639077339140:
await ctx.message.delete()
author = ctx.message.author
await ctx.bot.logout()
help
change message to ctx
and no need for ctx here ctx.bot.logout you can just use client
cilent is not defined
how do i make my bot listen for and copy discord ids
Like get the id of every author of a message, and may i ask why?
its client not cilent
Ciline.close?
like i want to paste a id and i want my bot to just copy the id i send howvwer it cant be a command
nah its ok haha
you can use an on_message and just have a suffix if you would like
Or you can also have a suffix and a check that checks the authors id
:D
that wont work
How so?
@bot.listen()
async def on_message(message) -> None:
if message.author.id == 979776516357488641 and message.content.endswith("_"):
global_var.append(message.content)
Just a simplified version
i mean like any id
how to check for the member inviter ? (on_member_join)
i want to paste an id and my bot just copy what i pasted
Why exactly? Yes, that does what you want just with a suffix to identify the special message?
i just need it to
also how do i make command for add author id?
Add the author id to where?
The user’s unique ID.
i have to rewrite this everytime
if i want to add someone id
Where do you want to add the id exactly? a container object?
so i have to add if ctx.author.id == 625899639077339140: to every command?
how can i just add it 1line
@check```
A decorator that adds a global check to the bot.
A global check is similar to a [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is applied on a per command basis except it is run before any command checks have been verified and applies to every command the bot has.
Note
This function can either be a regular function or a coroutine.
Similar to a command [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check"), this takes a single parameter of type [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context") and can only raise exceptions inherited from [`CommandError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError").
Example...
didnt know about this. thats useful
!d discord.ext.commands.is_owner
@discord.ext.commands.is_owner()```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that checks if the person invoking this command is the owner of the bot.
This is powered by [`Bot.is_owner()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.is_owner "discord.ext.commands.Bot.is_owner").
This check raises a special exception, [`NotOwner`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NotOwner "discord.ext.commands.NotOwner") that is derived from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
you can also use this
@discord.ext.commands.is_owner()
@mt.tree.command(name='profile', description='Check yours or a foes profile!')
@app_commands.describe(user='Provide a user (optional)')
@app_commands.describe(hide='Hide from other users?(yes by default)')
@app_commands.choices(hide=[
discord.app_commands.Choice(name='Yes', value=1),
discord.app_commands.Choice(name='No', value=2),
])
async def profile(interaction: discord.Interaction, user: discord.Member=None, hide: discord.app_commands.Choice[int]=1):
if user == None:
user = interaction.user
with open("users.json", "r") as f:
users = json.load(f)
await update_mny(users, interaction.user)
with open("users.json", "w") as f:
json.dump(users, f)
with open("lvl.json", "r") as f:
users = json.load(f)
await update_lvl(users, interaction.user)
with open("lvl.json", "w") as f:
json.dump(users, f)
if hide.value == 1:
profile = discord.Embed(title=f"{user}'s Profile")
await interaction.response.send_message(embed=profile, ephemeral=True)
if hide.value == 2:
profile = discord.Embed(title=f"{user}'s Profile")
await interaction.response.send_message(embed=profile)
Traceback (most recent call last):
File "/home/runner/miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 62, in profile
if hide.value == 1:
AttributeError: 'int' object has no attribute 'value'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'profile' raised an exception: AttributeError: 'int' object has no attribute 'value'
@commands.is_owner() both same?
Yeah, just one is more verbose
On top of the commands you want especially for you
can i use user id instead
You can use it for the specific commands, if you want all the commands use the global check
@commands.command()
@commands.check(add_Mod)
async def add_Mod(ctx, user:discord.Member=None):
if user == None:
await ctx.send("Please provide a user to add as a Mod!")
return
# First we'll make some functions for cleaner, more readable code #
def is_Mod(user_id):
## This function will check if the given id is already in the file. True if in file, False if not ##
with open('Mod.txt', 'r') as f:
if str(user_id) in f.read():
return True
else:
return False
def add_Mod(user_id):
## This function will add the given user id into the given text file, Mod.txt ##
with open('Mod.txt', 'a') as f: # 'a' is used for appending, since we don't want to overwrite all the ids already in the file
f.write(f"{str(user_id)}\n")
f.close()
# Now we put those functions to use #
if is_Mod(user.id) == True:
await ctx.send(f"The user {user} is already a Mod!")
else:
add_Mod(user.id)
await ctx.send(f"{user} added as a Mod!")
Your code can be restructured better, its quite unreadable and unpythonic and in some parts incorrect
And your implementation with txt files are a bit questionable, if you're going to store a bit of data why not making it easier and use JSON?
!code
!code
!pastebin
for some reason it says level is referenced before assignment if I select a user in the menu
I want to set my discord bot (made with discord.py) to restart every 10 minutes using os.execv(sys.argv[0], sys.argv) for testing purposes. I'm looking for an equivalent to Tkinter's root.after(milliseconds, command) that waits for a set amount of time before executing a command. Any ideas on how to implement this?
This is probably best done using a standalone, external process manager
does it make sense to add a global leaderboard and global rank command to a leveling bot?
replit projects run on shared machines. this means the IP address your bot is using the discord API from is shared with other people, who are also using the discord API. Cloudflare, the service that protects discord's api from DDoS attacks, sees this large number of requests, and blocks it.
It's one of the reasons that replit isn't good for hosting
are you hosting on a linux machine?
One of the better options for hosting things is to use a VPS, but you will never really find a good one for free. These are some good ones:
https://www.pythondiscord.com/pages/guides/python-guides/vps-services/
On different VPS services
All if not most free VPS will be shared instances, I doubt companies really want to fork out the money needed to supply everyone with a free dedicated server
how do i host replit on vps
you don't
You'll encounter that caveat in most places
yep. Nobody's going to give you free hosting, unless there's some kind of catch
anything free comes at the cost of userability
uptimerobot
If you want to, you could probably self host it, and run a computer in the corner of your basement or something with the bot running on it
?
???
which ide is fastest?
What does IDE have anything to do with hosting?
No idea
Repl.it seems to have given a lot of people a huge misconception with what IDEs actually do...
hard agree lmao
IDE is just your editor so to speak, your integrated editing development
Not a VPS
those are technically different things
idk what editing speed has to do with anything lmao
VSCode is just a text edtior, replit is a website with an editor in it, and cmd is a terminal
Basically just a hosted IDE
i found the right channel less gooo
welcome to the channel of misconceptions lmao
ok so basically my bots only command, u!username doesnt work;https://paste.pythondiscord.com/xuxikosole.py
ok
make sure to enable message_content intents
does it give you any errors
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, 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
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
ok ty
does uptimerobot actually work
yeah, for what it's supposed to be used for
idk
For what it was meant to do (not hosting bots) yea
nope
an unfortunate victim of the mob mentaility 😔
keep_alive() # Starts a webserver to be pinged.
token = os.environ.get("token")
bot.run(token) # Starts the bot
if you can get that working reliably, go for it ig. never used a phone as a server :p
Make sure to monitor your phone sometimes. It can get really hot
If you have a lithium battery it might even be dangerous
do you have your token in an .env file or is this code searching for something thats not there
I use replits env system, it actually is online
ur battery?
How much memory should typically be allocated to hosting a Discord bot 24/7?
how fitting, we were just discussing how unreliable replit is lol
how many events do you plan on seeing
I'm not really talking about your charge times, more so the heat of your phone which could cause some bad side effects
As phones don't usually come with fans and what not
Which servers usually equip themselves with
wasting money is better than wasting ur life
depends on what the bot is doing. If it's just call and respond stuff, usually about 1gb is enough for small bots. But if it's doing something thats memory intensive, or is in a lot of servers and needs to process a lot of things, more memory is required
xD
well my old desktop cant install anything :( (I use a 2011 mac that doesnt go past os 10.5)
I don't see my bot finding its way into any more than a couple dozen servers.
i have my level bot running on a VM with 2gb ram and i have 0 issues in 8 servers
2gb kind of overkill ngl
What sorts of things would be considered 'memory intensive'?
Was running in 50 or so servers and my peak was around 40~ mb
the lowest it would let me choose with the slider so i sent it lol ive actually got 2 bots running on it and never peak higher than 50%
how do u install discord.py module on pydroid??
What about CPU usage?
Bots that do caching, bots that do things with images, videos, or other attachments that are stored in memory, etc.
AttributeError: 'Intents' object has no attribute 'message_content'
I see, thanks.
My PC has 32GB of memory but sadly I left it at home when I moved out. If I had it with me then I could probably just self-host for the time being.
Should be careful about code as well, imagine someone makes a command O(n^2)
show me what you wrote
my vps is slow asf
you could self host 32-64 instances of your bot 😈
import os
from keep_alive import keep_alive
from discord import client,Intents
from discord.ext import commands
from lists import name_list, title_list
from urllib.request import urlopen
from random import randint
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(
command_prefix="u!", # Change to desired prefix
case_insensitive=True, # Commands aren't case-sensitive
intents=intents
)
bot.author_id = 928109349140824125 # Change to your discord id!!!
Nevermind that's time complexity not space complexity
Lol
try reinstalling discord.py. It looks like you have 1.7.3, you need to update to 2.0
k ty
it could also be space complexity 
bruh 2.0 bot got removed
what?
doesnt work
just stop being a nerd then
what did you do?
Yea In my response I meant time complexity but yea space complexity also is like that
they removed bot on v.2.0
?
pip install discord.py
But I find it hard to actually imagine someone doing O(n^2) space complexity in a command
do ```bash
pip install discord.py -U
Unless.... they are doing something too omega
What is O(n^2)?
pip install discord.py==1.7.3
time compelxity. "in what way or how quickly will this function reach infinity"
Why would you want that?
cuz im using it
If you're gonna use dpy, use 2.0+.
💀
no error
Earlier versions will stop working next year I believe.
passion is coding
hosts on replit
whoops wrong reply
yep, 1.7.3 uses gateway v6, which will stop working at some point
nah just playing because theres always someone in here with replit problems lol
Gateway 7
rlly?
thx, it was one of them and i didn't feel like looking 💀
yooo my bad it must have scrolled when i hit the reply button
Well you would be right anyways as Gateway 6 has long been deprecated
For some reason it's still the default version though ...
10-9 are the most current versions right now
but discord.py had an update 2.0 and they remove self botting u need to downgrade
You should be using 10 if you want the bleeding edge features like some interactions stuff
technically, it's just deprecated, not discontinued
Are you admitting to self-botting or something
@slate swan
What?
they're editing nukebot.py in their vscode status 💀

inb4 run nukebot -> 4m later get's locked
I doubt with vanilla discord.py you'll be able to selfbot easily anyways
Now that discord has the intents user accounts will find it harder to get around to getting messages
I think we should not be discussing self-bots or nuke-bots. Don't want the mods to get angry 
sarcastic
Anyways, which VPS services are generally recommended for bot hosting?
i recommend oracle cloud
here's a whole list
https://www.pythondiscord.com/pages/guides/python-guides/vps-services/
On different VPS services
Wow, thank you guys.
ehhhhhhhh, I mean you do get a free VPS in exchange for all your personal data
eehhhhhh everything about me is already on the internet they can have it
How the heck can one be "self hosting on Replit" lol
I remember once I was working on a project with a partner during class and I was bored and started playing around with the shell, and I did rm -rf / --no-preserve-root just for fun to see if it would work. It didn't, but it did delete all of our project.
how can I mention slash commands
</command name : command ID>
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
hosting bot on mobile phone
no, because it deleted all the files
and how do I get the cmd id?
looks like you right click this bar
its great as long as its not wrong
Props to the people who coded stack overflow without using stack overflow
and as long as the post you find that has the exact same error as you for 2009 has an answer

🙏
char e[999999999999999999999];
Always fun when you find a post with no answers and just a comment with "nvm fixed it"
this is very well put together and detailed. someone did a lot of digging and i like it
chad stack overflow joke
well yeah it was a lawsuit
fair point. official docs do be official looking
!d discord.Message.mentions
A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.
Warning
The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.
this one?
anybody got a cooldown thats specified per user that would work in an on_message?
!custom-cooldown
Cooldowns in discord.py
Cooldowns can be used in discord.py to rate-limit. In this example, we're using it in an on_message.
from discord.ext import commands
message_cooldown = commands.CooldownMapping.from_cooldown(1.0, 60.0, commands.BucketType.user)
@bot.event
async def on_message(message):
bucket = message_cooldown.get_bucket(message)
retry_after = bucket.update_rate_limit()
if retry_after:
await message.channel.send(f"Slow down! Try again in {retry_after} seconds.")
else:
await message.channel.send("Not ratelimited!")
from_cooldown takes the amount of update_rate_limit()s needed to trigger the cooldown, the time in which the cooldown is triggered, and a BucketType.
thanks
well thats a global cooldown isnt it? im trying to make one for a level system where if that specific user sends a message within 5 seconds of another message it wont register, but other users can still send a message that gets registered
Look at the bucket type
it's not documented, but you could create your own CooldownMapping
im not trying to dive into undocumented territory lol
then you've probably hit a wall
looks like this does just that actually
yea im gonna put that in and see how she goes
prefix = "!"
client = commands.Bot(command_prefix = prefix , intents = discord.Intents.all())
status = cycle(['gbot is listening'])
@client.command()
async def pat(ctx):
await ctx.send('bark bark!!')
why this is not working anyone
Does it give any errors?
so in this, the from_cooldown(1.0, 60.0 is that saying one update in 60 seconds?
import discord
import os
import random
from discord.ext import commands, tasks
from itertools import cycle
import pytz
import time
prefix = "!"
client = commands.Bot(command_prefix = prefix , intents = discord.Intents.all())
status = cycle(['gbot is listening'])
@client.event
async def on_ready():
await client.change_presence(status=discord.Status.idle, activity=discord.Game('With Your Mom'))
print("token is online")
print("")
time.sleep(0.5)
print('all systems are booted up , ready to be online !')
@client.event
async def on_message(message):
if message.author == client.user:
return()
if message.content.startswith("!ur on ?"):
await message.channel.send("Yes Im On , Playing With Ur Mom")
@client.command()
async def role_assign(ctx , message , roles):
if message.content == roles:
role = discord.utils.find(lambda m: message == roles, discord.Guild.roles)
message.channel.send(role.id)
@client.command()
async def pat(ctx):
await ctx.send('bark bark!!')
my_secret = os.environ['token']
print("booting the system")
print("")
time.sleep(0.5)
print("systems are online")
print("")
client.run(os.getenv("token"))
@client.event
async def on_message(message):
if message.author == client.user:
return()
if message.content.startswith("!ur on ?"):
await message.channel.send("Yes Im On , Playing With Ur Mom")
this part wworks
yea im running it on replit
this is your problem
doesnt solve problems inside the code though lol
kk
Windows
@client.event
async def on_message(message):
if message.author == client.user:
return # no parentheses
okay
jeez what? the kill is used to force stop a process with its ID
i get that 😂
💣
where to place this peice of code
osama coding timer
heyo how do I get bot in my cog for this decorator?
@bot.tree.error
add the bomb too \💣
you have to set bot.tree.on_error to a coroutine (your callback) in your init
on my init where
your cog's init
a coroutine is a function that's async
async def on_app_command_error(self, interaction: discord.Interaction, error: app_commands.AppCommandError):
if isinstance(error, app_commands.CommandOnCooldown):
error_embed = discord.Embed(
title=error,
color=discord.Color.red())
await interaction.response.send_message(embed=error_embed)
This is the function I am trying to put the decorator on
in your init, you gotta set tree.on_error to that coroutine then
don't call it though
now what is that 😭
is there a more proper way to exit a chunk of code than doing this: if undesirable: return
bro how to solve that issue
you literally have to type 2 characters ._.
I don't think so. Is there something specific you were expecting?
could you elaborate a bit? Errors are raised, they're not typed btw
no i just wanted to make sure since you can return specific values with stuff. wasnt sure if just a blank return is the way i should be doing it or if theres something else specifically for that
You can listen to the on_command_error event
@bot.slash_command(description="Buy things!")
async def buy(interaction: nextcord.Interaction, option: str = nextcord.SlashOption(description="Item Name", required=True)):
p2 = interaction.user.id
with open('Data.json') as json_file:
json_decoded = json.load(json_file)
p7 = json_decoded["Data"][str(p2)]["Coins"]
if option.lower() == "watermelon":
if (json_decoded["Data"][str(p2)]["Coins"] >= 50):
json_decoded["Data"][str(p2)]["Potato"] += 1
msg = await interaction.send(f"Successfully bought watermelon, your balance is now **{p7}** ()!")
elif option.lower() == "potato":
if (json_decoded["Data"][str(p2)]["Coins"] >= 100):
json_decoded["Data"][str(p2)]["Potato"] += 1
msg = await interaction.send(f"Successfully bought potato, your balance is now **{p7}** ()!")
else:
await interaction.send("⚠ Error: Invalid Syntax (Please use /shop for reference!)")
I'm trying to make it so when you put "watermelon" or "potato" into the option it adds one potato or watermleon to the json if they have enough coins
it doesn't send an error but it says the application doesn't respond
no idea what to do next
You can raise an error if you want to too. It really just depends on why you're exiting the function
As in the traceback?
just exiting because of the custom rate limit is all. i just wanted it to exit the function and do nothing else
print or ctx.send()?
im not sure about nextcord but with discord.py itll send that when you dont send a response to the slash command with interaction.response.send_message
im losing my temper
consider using literal/choice arguments instead of a plain string argument. Any tracebacks?
ohh i seee why
a command is not an event
dayum using api is hard man
Nope no errors
no, that'll just return the raw string with no additional arguments
does it respond with the messages you intend on sending
Could you give me an example of literal/choise arguments please?
nope just application is not responding
it isnt responing to msg
I'm not too sure if nextcord also has this, probably does
from typing import Literal
@bot.slash_command(...)
async def buy(..., option: Literal["Argument 1", "Argument 2"]):
...
Traceback (most recent call last):
File "main.py", line 306, in <module>
class View(discord.ui.View):
File "main.py", line 311, in View
async def tes(interaction: discord.Interaction):
File "/home/runner/miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 889, in decorator
command = Command(
File "/home/runner/miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 685, in __init__
self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.__globals__)
File "/home/runner/miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 381, in _extract_parameters_from_callback
raise TypeError(f'callback {func.__qualname__!r} must have more than {required_params - 1} parameter(s)')
TypeError: callback 'View.tes' must have more than 1 parameter(s)
class View(discord.ui.View):
def __init__(self, *, timeout: float = 3600.0):
super().__init__(timeout=timeout)
@mt.tree.command(name='menu', description='Opens the menu!')
async def tes(interaction: discord.Interaction):
select = Select(min_values=1, max_values=1, options=[
discord.SelectOption(
label="Profile", emoji='🎲', description='cloudy weather'),
discord.SelectOption(label="Rainy", description='rainy weather')
])
yea u should focus on america rn
you're probably getting a missing required argument error
How would I reference argument 1 or argument 2?
im not getting any error or anything
trying to make it so when I do
view = View()
it attaches the menu but I get this error(the message replied to it)
that is not how you create a select. Please view this example and the documentation:
https://github.com/Rapptz/discord.py/blob/master/examples/views/dropdown.py
https://discordpy.readthedocs.io/en/stable/interactions/api.html#discord.ui.Select
old osama hijacked planes , new osama will be a coder and hack their systems then make 1000s of planes fall
select?
lee oni-chan help me
assuming that you're using slash commands, option will be either Argument 1 or Argument 2
select = the menu is a select menu
yea i see now
I'm asking like how would you do if choice == 'argument 1':
thanks
use interaction.response.send_message, you gotta respond to interactions and that's how
just like that, be careful with case sensitivity though
so replace choice with option, using your example?
can i have a lil example bro
you can still have the argument named choice, just take a look at the type hint
!d nextcord.InteractionResponse.send_message you can have docs :)
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, delete_after=None, allowed_mentions=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
class Dropdown(discord.ui.Select):
def __init__(self):
# Set the options that will be presented inside the dropdown
options = [
discord.SelectOption(label='Red', description='Your favourite colour is red', emoji='🟥'),
discord.SelectOption(label='Green', description='Your favourite colour is green', emoji='🟩'),
discord.SelectOption(label='Blue', description='Your favourite colour is blue', emoji='🟦'),
]
# The placeholder is what will be shown when no option is chosen
# The min and max values indicate we can only pick one of the three options
# The options parameter defines the dropdown options. We defined this above
super().__init__(placeholder='Choose your favourite colour...', min_values=1, max_values=1, options=options)
async def callback(self, interaction: discord.Interaction):
# Use the interaction object to send a response message containing
# the user's favourite colour or choice. The self object refers to the
# Select object, and the values attribute gets a list of the user's
# selected options. We only want the first one.
if self.name == 'Red':
await interaction.response.send_message("red", ephemeral=True)
Traceback (most recent call last):
File "/home/runner/miner-bot/venv/lib/python3.8/site-packages/discord/ui/view.py", line 425, in _scheduled_task
await item.callback(interaction)
File "main.py", line 325, in callback
if self.name == 'Red':
AttributeError: 'Dropdown' object has no attribute 'name'
what are you trying to check the name of
i wrote this one so let me see if i can help :p 
lets go!!
the first one
i tried
self.value[0]
Your callback should take select as the 3rd argument:
async def callback(self, interaction: discord.Interaction, select: discord.ui.Select) -> None:
if select.values[0].name == "Red":
...
wym
aside from just adding more spaces? lol
doesnt work
oh wait I didnt do send_message right
@sick birch
async def callback(self, interaction: discord.Interaction, select: discord.ui.Select) -> None:
if select.values[0].name == "Red":
await interaction.response.send_message("Red", ephemeral=True)
this doesnt send the message
Try print(select.values) to see what it prints
nothing just says it failed
send_message(content='red', ephemeral=True)
if you want to do it dynamically, you can do something like
f"{'Shovel':8} :lock:"
where you can change 'Shovel' for a string variable. Else, just use spaces
whats this do
nope
I've got no clue how to explain it if I'm being honest. I'm quite newbie to it. F-strings are quite the marble :o
then do this and see what it prints
where did you put it
replaced the interaction.response.send_message
youre not making it to the send message part
thats the point of the print
put it before if select.values
the line above it
below the callback line
inline with if
not self.values
what
select.values
o
nothing
did you run the bot and select something from the menu
Are you re-running the command and using the new select menu or are you using an older select menu from before?
I mean, on discord
and this is inside the DropdownView class?
this says class dropdown not dropdownview
Try printing self.values
i alr did
he does on line 318
That's select.values
i also did self.values
Since this is inside a ui.Select subclass
@fading marlin
self.bot.tree.on_error = CommandErrorHandler.on_app_command_error
``` Is this what you're talking about?
@fading marlin name 'Literal' is not defined
@sick birch you good bro?
Hi, i get 400 bad request no content whenever i try to send an embed msg, heres my code:
embedMsg = discord.Embed(title=config.TITLE, description=config.DESCRIPTION, color=0x00FFFF)
if message.content.startswith('test'):
await message.channel.send(embed=embedMsg)
TITLE = "test"
DESCRIPTION = "PLACEHOLDER TEXT"
Traceback (most recent call last):
File "/Users/ellalbrys/PycharmProjects/EconomyDiscordBot/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1089, in wrapper
await self._call(interaction)
File "/Users/ellalbrys/PycharmProjects/EconomyDiscordBot/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1244, in _call
await self.on_error(interaction, e)
TypeError: CommandErrorHandler.on_app_command_error() missing 1 required positional argument: 'error'
``` Trying to create a cooldown. I'm close, but idk how to fix this
Handler
@commands.Cog.listener()
async def on_app_command_error(self, interaction: discord.Interaction, error: app_commands.AppCommandError):
if isinstance(error, app_commands.CommandOnCooldown):
error_embed = discord.Embed(
title=error,
color=discord.Color.red())
await interaction.response.send_message(embed=error_embed)
else:
print("error:", error)
And the error is just from @app_commands.checks.cooldown(1, 60)
@commands.Cog.listener()
@cmdname.error
async def on_cmdname_error(interaction: discord.Interaction,
error: app_commands.AppCommandError):
if isinstance(error, app_commands.CommandOnCooldown):
await interacti
try this and replace cmdname with ur cmd name
as this slash command wold be sell
on_app_command_error isnt an event
use the @tree.error decorator
class Dropdown(discord.ui.Select):
def __init__(self):
# Set the options that will be presented inside the dropdown
options = [
discord.SelectOption(label='Red', description='Your favourite colour is red', emoji='🟥'),
discord.SelectOption(label='Green', description='Your favourite colour is green', emoji='🟩'),
discord.SelectOption(label='Blue', description='Your favourite colour is blue', emoji='🟦'),
]
super().__init__(placeholder='Zio Miner Menu', min_values=1, max_values=1, options=options)
async def callback(self, interaction: discord.Interaction, select: discord.ui.Select) -> None:
print(self.values)
if select.values[0].name == "Red":
await interaction.response.send_message("Red", ephemeral=True)
why isnt this printing or responding?
I can't use @tree
why not
do you want to handle errors globally, for this cog, or for one command?
Globally
class DropdownView(discord.ui.View):
def __init__(self):
super().__init__()
self.add_item(Dropdown())
view = DropdownView()
await interaction.response.send_message("", view=view, ephemeral=True)
someone please help me figure out why this menu isnt working
what happens?
@upbeat gust perfect, thanks
@upbeat gust
could you help?
view = DropdownView()
await interaction.response.send_message("", view=view, ephemeral=True)
class Dropdown(discord.ui.Select):
def __init__(self):
options = [
discord.SelectOption(label='Red', description='Your favourite colour is red', emoji='🟥'),
discord.SelectOption(label='Green', description='Your favourite colour is green', emoji='🟩'),
discord.SelectOption(label='Blue', description='Your favourite colour is blue', emoji='🟦'),
]
super().__init__(placeholder='Zio Miner Menu', min_values=1, max_values=1, options=options)
async def callback(interaction: discord.Interaction, select: discord.ui.Select):
print(options.values)
if options.values[0].name == "Red":
await interaction.response.send_message("Red", ephemeral=True)
class DropdownView(discord.ui.View):
def __init__(self):
super().__init__()
self.add_item(Dropdown())
this menu doesnt do anything, it doesnt print or send a message
-> Running in aa9c07c9cc02
2
An error occurred during configuration: option use-feature: invalid choice: 'content-addressable-pool' (choose from '2020-resolver', 'fast-deps', 'in-tree-build')
3
what does that mean
@tasks.loop(seconds = 10) # repeat after every 10 seconds
async def myLoop(ctx):
print("restarting")
os.system("python bothappy.py")
I added this to my discord bot and I get this error: RuntimeError: no running event loop
someone pls
view = View()
await interaction.response.send_message(embed=profile2, ephemeral=True, view=view)
question, how can I add the menu into the field?
got it nvm
!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.
make sure ur passing it in as a keyword argument
embed = discord.Embed(
description= 'Board',
color = discord.Color.blue())
embed.set_image('https://static.wikia.nocookie.net/monopoly/images/a/a5/Monopoly_Board_Game_%28UK%29.jpg/revision/latest/scale-to-width-down/1000?cb=20220120173735')
embed.set_author(name= 'Lobby',
icon_url = ctx.author.avatar.url)
embed.set_footer(text = 'Go grab some drinks')
await ctx.send(embed=embed)
embed.set_image(url=…)
AppCommands don't have a hidden attribute?
In discord.py, does a view's timeout countdown get reset whenever a user clicks a button in that view, or is it just a single countdown?
random_activity = ['Zio Miner', '/help', f'in {len(mt.guilds)} guilds!']
why is it saying 0 guilds?
Anyone can just tell why with just that amount of info, huh
Reset
Thanks
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
def get_prefix(bot, message):
prefixes = ['!']
return commands.when_mentioned_or(*prefixes)(bot, message)
initial_extensions = []
bot = commands.Bot(intents = discord.Intents.all(),
command_prefix=get_prefix,
description='Phoenix 2 iOS information bot',
owner_ids= [352986404621647873])
for filename in os.listdir('./cogs'):
if filename.endswith (' .py'):
initial_extensions.append("cogs." + filename[:-3])
async def setup_hook(self):
for extension in initial_extensions:
try:
bot.load_extension(extension)
except Exception as e:
print(f'Failed to load extension {extension}.', file=sys.stderr)
traceback.print_exc()
@bot.event
async def on_ready():
print('We have logged in as {0.user}'.format(bot))
try:
synced = await bot.tree.sync()
print(f"Synced {len(synced)} command(s)")
except Exception as e:
print(e)
game = discord.Game("Phoenix II")
await bot.change_presence(status=discord.Status.online, activity=game)
print(f'Successfully logged in and booted...!')
class SimpleCog(commands.Cog, name="Simple Commands"):
"""SimpleCog"""
def __init__(self, bot):
self.bot = bot
@app_commands.command(name="source", description="GitHub repository link")
async def source(self, interaction: discord.Interaction):
src = "https://github.com/NinjaPanda263/Roc-Bot"
await interaction.response.send_message(src)
async def setup(bot):
bot.add_cog(SimpleCog(bot))
I am having trouble getting my commands in cogs to sync. Working on adding slash commands.
please ping if you respond, ty
Pycord has automatic tree sync doesn't it
for command in s: a += 1 what, why not use len(s) lol
In pycord the sync is done automatically
It's not dpy where you gotta do it manually
app_commands.AppCommand is not a decorator
!d discord.app_commands.command is
@discord.app_commands.command(*, name=..., description=..., nsfw=False, auto_locale_strings=True, extras=...)```
Creates an application command from a regular function.
how to ignore this error
You don't need it at all
Listen for on_command_error event
@bot.listen()
async def on_command_error(ctx, error):
if isinstance(error, commands.CheckFailure):
# handle
else:
raise error```
!rule tos
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
IndentationError: expected an indented block after 'if' statement on line 34
view = View()
view.add_item(select)
profile2.set_thumbnail(url=user.avatar.url)
await interaction.response.send_message(embed=profile2, view=view, ephemeral=True)
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'mine' raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.embeds.0.fields.0.name: This field is required
You need to set name and value to each of the embed fields
reading through that, do i have to run the bot in every file for it them to be synced?
i did
?
profile2.add_field(name='', value=f'**Pickaxe** {pick}\n{shovelrndm}\n{drillrndm}\n{fistrndm}')
profile2.add_field(name='Multipliers', value=f'{moneymulti}\n{blockmulti}\n{xpmulti}\n{rubymulti}')
profile2.set_author(name=f"{user.name}'s profile", icon_url=user.avatar.url)
You only need to add cogs and sync the tree
oh wait
You have empty name
yea thats what i have but they arent being added
In this code there's no tree sync
ive added it in
bot is not defined
client variable naming 😒
oh ye i did
Who uses client 💀
To where
This code is in a function. Please tell me the purpose of that function
Make them global from the beginning
Pycord has automatic sync and you can't do anything about it
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: '<' not supported between instances of 'str' and 'int'
Without touching the protected members
Error says it all
This is the first time I encounter such an error.
class SimpleCog(commands.Cog) -> None:
def __init__(self, bot: commands.Bot):
self.bot = bot
@app_commands.command(name="source", description="GitHub repository link")
async def source(self, interaction: discord.Interaction) -> None:
src = "https://github.com/NinjaPanda263/Roc-Bot"
await interaction.response.send_message(src)
async def setup(bot: commands.Bot) -> None:
bot.add_cog(SimpleCog(bot))
await bot.tree.sync()
this is what i have @vale wing
So what? It describes what's wrong with your code and higher in traceback there's a concrete line where it occurs
In dpy the syncing should be done in a separate command, but before do the sync in setup_hook method of your bot subclass (just to register the sync command)
You do setup_hook wrong btw
@vale wing how to ignore this also
Should be like this
class MyBot(commands.Bot):
async def setup_hook(self):
...
bot = MyBot(...)
Add elif isinstance(error, commands.BadArgument), analogically for every exception you need to handle
still cant
What you did
2 client event at near line wont be worked
Man
huh
You don't need to create a separate listener for every damn exception
Just extend if-elif-else block
where do i add this elif
Basic python smh
!e ```py
a = 69
if a == 10:
print("ten")
elif a > 10:
print("more")
else:
print("less")
@vale wing :white_check_mark: Your 3.11 eval job has completed with return code 0.
more
damn ty
pffft
damn
😳
import discord
from discord import app_commands
class aclient(discord.Client):
def __init__(self):
super().__init__(intents=discord.Intents.default())
self.synced = False
async def on_ready(self):
await self.wait_until_ready()
if not self.synced:
await tree.sync(guild=discord.Object(id=990534020880277514))
self.synced = True
print(f"We have logged in as {self.user}")
client = aclient()
tree = app_commands.CommandTree(client)
@tree.command(name="hello",
description="Hello user",
guild=discord.Object(id=990534020880277514))
async def hello(interaction: discord.Interaction, name: str):
await interaction.response.send_message(f"Hello {name}! I was made by me!")
client.run(
'token')
the bot is online but i cant see the command
Define the tree in the __init__ if you're going to subclass the client
https://github.com/Rapptz/discord.py/blob/master/examples/app_commands/basic.py#L13-L20
examples/app_commands/basic.py lines 13 to 20
# A CommandTree is a special type that holds all the application command
# state required to make it work. This is a separate class because it
# allows all the extra state to be opt-in.
# Whenever you want to work with application commands, your tree is used
# to store and work with them.
# Note: When using commands.Bot instead of discord.Client, the bot will
# maintain its own tree instead.
self.tree = app_commands.CommandTree(self)```
what should I use as intents?
How to fix this?
@client.listen()
async def on_message(message):
if not message.guild:
embed=discord.Embed(title="DM this Bot is not allowed!", url="", description="whoops this isn't in a server this is in dms", color=discord.Color.blue())
await message.author.send(embed=embed)
return
Error: ```
await message.author.send(embed=embed)
AttributeError: 'ClientUser' object has no attribute 'send'
anyone know any servers where i can hire python devs
The bot can't DM itself
how to fix?
i mean the bot should send the person a dm who wrote. It just works but it comes also this error
Make it ignore if the author is the bot
Okay thats simple. Thanks
discord.Intents.all()
from discord.ext import commands
intents = discord.Intents(messages=True)
intents.members = True
client = commands.Bot(command_prefix='$', intents=intents)
TOKEN =
@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(TOKEN)```
doesn't show any error but zero response while sending $hello in a text channel
any idea how to fix that?
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
What library is this
!d discord.Intents.message_content
Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:
• The message was sent by the client
• The message was sent in direct messages
• The message mentions the client
This applies to the following events...
And you have to enable the intents in the Dev portal also
do you mean this?
Yes
Can I dm a person where i have Discord Tag only as input?
For example a String with Flouu#8782
no
IDs
!d emoji
ofcourse they can
is it a command?
!f discord.ext.commands.UserConverter.convert
You are not allowed to use that command here. Please use the #bot-commands channel instead.
!d discord.ext.commands.UserConverter.convert
await convert(ctx, argument)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a [`CommandError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError") derived exception as it will properly propagate to the error handlers.
Any idea on how to make bot use commands of another bot?
Wdym
when I write /bump it triggers DISBOARD command but when bot writes it, nothing happens
if message.content.startswith("!bump"):
await message.channel.send("/bump")
This is what I use
Bots can't use slash commands
whats the code for upload emoji
No i will get it from the DB
!d discord.Guild.create_custom_emoji
await create_custom_emoji(*, name, image, roles=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a custom [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji") for the guild.
There is currently a limit of 50 static and animated emojis respectively per guild, unless the guild has the `MORE_EMOJI` feature which extends the limit to 200.
You must have [`manage_emojis`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_emojis "discord.Permissions.manage_emojis") to do this.
Other question: How to handle a missing argument. If arg == None: Does not work....
Set default argument
Should i do it with try except?
mhhh
Or error handler
Could you send me an example
About default arguments or error handler
Default is working fine for me, but if you think error handler is the better choice, pls send me example :=
🙂
A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
why can't you save the ID in the db?
what if someone changes their username?
Hmmm thought it would be easier for the Users. Dont know if everyone knows their ID or how to get
!d discord.Client.get_user
get_user(id, /)```
Returns a user with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
how do i pip install PIL
yeah ik
!pypi Pillow
How to put in 2 Arguments with error handling, so that i can send a message if someone send for example 3 Args or 0
im running my bot on replit
What's the problem
i dont know how to install it
The same way you install discord.py
i forgot how
Replit will install most available Python and Javascript packages using the universal package manager.
You didn't install it
pip istall PIL?
Could someone help me?
How to put in 2 Arguments with error handling, so that i can send a message if someone send for example 3 Args or 0
Its module name is PIL but the package's name in pypi is Pillow
There's package manager in replit
here comes the best part how do i even save photo on replit for PIL
Save from what
What is a lik

how do i even save photo on replit for PIL :/
Make a request to the image link, then get the image data and put them in io.BytesIO, then use PIL.Image.open to open it
huh
what is io
!d io.BytesIO
class io.BytesIO(initial_bytes=b'')```
A binary stream using an in-memory bytes buffer. It inherits [`BufferedIOBase`](https://docs.python.org/3/library/io.html#io.BufferedIOBase "io.BufferedIOBase"). The buffer is discarded when the [`close()`](https://docs.python.org/3/library/io.html#io.IOBase.close "io.IOBase.close") method is called.
The optional argument *initial\_bytes* is a [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object) that contains initial data.
[`BytesIO`](https://docs.python.org/3/library/io.html#io.BytesIO "io.BytesIO") provides or overrides these methods in addition to those from [`BufferedIOBase`](https://docs.python.org/3/library/io.html#io.BufferedIOBase "io.BufferedIOBase") and [`IOBase`](https://docs.python.org/3/library/io.html#io.IOBase "io.IOBase"):
Import it
import io?
yes
what do i even put in io.BytesIO()
Image bytes
what is that 0 & 1?
i tried googling it but i still dont understand ;-;
i need help
how to make reqest
try removig "" for ("10403...")
Are you gonna make it for your discord bot
i just want to send the picture after editing it
so im not sure yes or no
from PIL import Image
from urllib.request import urlopen
url = "https://python-pillow.org/images/pillow-logo.png"
img = Image.open(urlopen(url))
```found this from doc
lemme try
how do i make the bot activity be watching and then number of guilds the bot is in
code
url = 'https://static.wikia.nocookie.net/monopoly/images/a/a5/Monopoly_Board_Game_%28UK%29.jpg/revision/latest/scale-to-width-down/1000?cb=20220120173735'
img = Image.open(urlopen(url))
await ctx.send(img)
looks legal? @naive briar
What do you mean
wait no
this is the output
how do i make the bot activity be watching and then number of guilds the bot is in
??
you need to send a discord.File, not PIL.Image.Image
IO stands for Input Output
how do i even send a discord file
Bot.get_channel is returning None
.send(file= your file object)
oo
??
!d discord.Client.guilds
property guilds```
The guilds that the connected client is a member of.
Get the len of that
thankss!!!'
url = 'https://static.wikia.nocookie.net/monopoly/images/a/a5/Monopoly_Board_Game_%28UK%29.jpg/revision/latest/scale-to-width-down/1000?cb=20220120173735'
img = Image.open(urlopen(url))
await ctx.send(file=img)
Ive never worked with translator but let me check the docs
what kind of error is to_dict 💀
Did you read what sarth said
i did
bro it needs a discord.File object
not a pillow image, convert the image to a file obj first
bruh
🥹
!d discord.File
class discord.File(fp, filename=None, *, spoiler=..., description=None)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for sending file objects.
Note
File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
I have no words
dont worry :D
i dont even understand what this is
then learn the bascis
instead of failing at maling. dc bot
🥹
maling
help
quite opposite
oh yea
def foo(ctx, time: int)
!foo @slate swan
I don't understand...
what's wrong here?
learn oop import asyncio on top and make ur first positional self inplace of ctx
(self, ctx,member... and so on
@bot.event
async def on_ready():
print(f"{bot.user.name} is online!")
guilds = bot.guild.guilds
await bot.change_presence(status=nextcord.Status.idle, activity=nextcord.Activity(type=nextcord.ActivityType.watching, name="{} guilds!".format(guilds)))```
AttributeError: 'Bot' object has no attribute 'guild'
What even is .guild
And it returns a list
You have to get the len of it
no
does anyone know i can make my bot only copy the ids i send to it, but i only want it to do ids. this is how far ive come
Wdym "copy"
i want to send a id in chat and for my bot to literally just copy it and send the id i sent into chat
Change message variable to msg so it doesn't mess with function args, and then do message.channel.send(msg)
Since you didn't mention what kind of IDs; you can make the bot check your messages for specific strings (the length, and its specific characters) and then send it again
You can use len function and regex ^ for this
yes how do u do this
↑
Waht
how do i connect them
Connect them?
Connect what
In what format are they giving the color
hex code
but either the staff role
if colour:
embed.colour(teal = 0x1abc9c,
dark_teal = 0x11806a,
green = 0x2ecc71,
dark_green = 0x1f8b4c,
blue = 0x3498db,
dark_blue = 0x206694,
purple = 0x9b59b6,
dark_purple = 0x71368a,
magenta = 0xe91e63,
dark_magenta = 0xad1457,
gold = 0xf1c40f,
dark_gold = 0xc27c0e,
orange = 0xe67e22,
dark_orange = 0xa84300,
red = 0xe74c3c,
dark_red = 0x992d22,
lighter_grey = 0x95a5a6,
dark_grey = 0x607d8b,
light_grey = 0x979c9f,
darker_grey = 0x546e7a,
blurple = 0x7289da,
greyple = 0x99aab5)```
```Ignoring exception in command <nextcord.application_command.SlashApplicationCommand object at 0x00000199C76033A0>:
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\application_command.py", line 863, in invoke_callback_with_hooks
await self(interaction, *args, **kwargs)
File "c:\Users\PC\Desktop\Appelsy Bot\main.py", line 78, in embed_create
embed.colour(teal = 0x1abc9c,
TypeError: 'NoneType' object is not callable
The above exception was the direct cause of the following exception:
its an embed creator
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
so the members wont have to write a hex code they will just write red and the embed will be red
why
@client.command(pass_context=True)
async def unbanall(ctx):
guild=ctx.message.guild
ban_list=await client.get_bans(guild)
await client.say('Unbanning {} members'.format(len(ban_list)))
for member in ban_list:
await client.unban(guild,member)
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Bot' object has no attribute 'get_bans'
this happens when i try to install discord.py
Issue With Logging issues :/. The Issue is supposed to go into a log file, but nope , it doesnt.
Code:
@bot.command()
async def reportIssue(ctx,Issue:str):
logging.info((str(ctx.message.author.id)+Issue))
await ctx.reply('Issue Logged!')
@torn sail
Why add the select menu to another view
Nvm I'm dumb. Haven't worked with select menus enough
same super new to it first time trying them out
You want self.add_item(StartOfTicket())
have no idea what im doing but happy to learn
Do this instead of self.add_view
@mighty pilot
At the very bottom where the light bulb is
You want self.add_item(StartOfTicket())
Instead of add_view
thanks it works now
I think for this you may have to do something like
if colour == 'red': clr = '0xe74c3c'
Then in your embed, color = clr
TYSM
Were you able to find one?
Reddit has some pages where people can post about bot requests
discord.py buttons are hard nothing works for mee
They kinda just 'clicked' for me at some point, now the majority of my current project's code is inside buttons instead of the actual commands.
if shovel != 0:
shovelrndm = random.randint(1, 100)
if rubychance >= 1 and rubychance <= 30:
rubyrndm = random.randint(1, 10)
if rubymulti == 0:
rubymulti == 1
rubyrndm = rubyrndm * rubymulti
await interaction.response.send_message(f"ruby rndm {rubyrndm}\nruby chance {rubychance}\nshovel random {shovelrndm}")
Traceback (most recent call last):
File "/home/runner/miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 442, in mine
rubyrndm = rubyrndm * rubymulti
UnboundLocalError: local variable 'rubyrndm' referenced before assignment
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'mine' raised an exception: UnboundLocalError: local variable 'rubyrndm' referenced before assignment
someone please tell me why its saying this
Try moving the rubyrndm = rubyrndm * rubymulti in line with your rubymulti == 1
Or add in an else: statement to match your if
To give it different values if they don't qualify for your if
why wont my dropdown send a embed when i click it
You should be using interaction for example you can edit the original message with another view
wym
I think they're referring to the callback near the top
Oh this is not an Select subclass?
The top is a select class then the view that adds it below
If it was then you can just use self.values and not pass it to callback (unsure if that even works)
sometimes I still look into this channel and see
get the callback outside of your __init__
and then i wanna unsee everything
same
this is my dropdown
yeah get the callback out there
in the class but not in the __init__
it's also self.values
not select
!d discord.ui.Select.callback idk anymore what this is passed
!d discord.ui.Select.callback
await callback(interaction)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The callback associated with this UI item.
This can be overridden by subclasses.
remove select from the args completely
stated here
nice
uh okay ill try ig
this is the main reason I don't check in here anymore
Also you shouldn't use time.sleep, it's blocking
Hey while there's people here that know more than me, I'm having a problem editing a message my bot sends. It's a level bot so a user sends a message in a channel, then in the bot spam channel it sends a message with a button view. I'm trying to disable the buttons after the view times out and can't figure out how to do that from inside the view since the event isn't an interaction it's just a message that the bot sends in a channel
One sec I'll send what I have
I have the on_timeout made I just don't know how to grab the message object that's sent inside the on_message
oh okay, well send code
ModuleNotFoundError: No module named 'discord'
How do i fix this error?
heres where the message is sent from inside the on_message
pip install discord
in cmd
pip install discord.py in your terminal
I also did that but then I get this error no matter what. I also made sure to have the latest versions of pip.
note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for yarl
Failed to build multidict yarl
ERROR: Could not build wheels for multidict, yarl, which is required to install pyproject.toml-based projects
get python 3.10
I do
oh
Your callback function is in __init__
Move it down
ah
its not reading the clr
whats the error
@naive briar ? like this right
no error
your callback should be inside your select class
Use a dict :|
any help on this?
^
wdym how
traceback? could you show the entire code?
basically i just dont know how to grab the message object from the original message sent inside the on_message so i can edit it to disable the buttons on timeout
🥹
!e
colours = dict(black="0x000000", white="0xffffff")
print(colours.get("black"))
print(colours.get("red", "default_colour"))
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0x000000
002 | default_colour
so where to put in im fr confused rn
what's the point of storing hex as a string

