#discord-bots
1 messages · Page 1067 of 1
A verified and famous bot (Dyno, ig?) ran an eval to by mistake delete every category in every server or smth. Discord saved most of the servers by changing the token and the damage was only done in a handful of servers
import motor
import discord
from webserver import keep_alive
import os
import requests
from discord.ext import commands
from discord.ext.commands import has_permissions
import urllib
import json
from motor.motor_asyncio import AsyncIOMotorClient
with open("./data.json") as file:
data = json.load(file)
cluster = AsyncIOMotorClient(data['mongo-uri'])
db = cluster["main"]
cursor = db["tutorial"]
client = commands.Bot(command_prefix = "-monkey ")
@client.command()
async def identity(ctx):
check = await cursor.find_one({"id": ctx.author.id})
if check is None:
insert = {
"id": ctx.author.id, "name": ctx.author.name, "tags": ctx.author.discriminator, "monkeybux": 50
}
await cursor.insert_one(insert)
mbed = discord.Embed(
title="NOW YOU ARE OFFICALLY REGISTERED AS A MONKEY",
description="be a good monkey ok"
)
await ctx.channel.send(embed=mbed)
else:
mbed = discord.Embed(
title="YOU ALREADY ARE A MONKEY...",
description="bro you cant have 2 personalities"
)
await ctx.channel.send(embed=mbed)
How do you install pycord on replit?
it auto installs... There is package manager
@slate swan
There's a package manager
now try to be clear
I was trying but it was installing d.py instead.
Because of the same namespace. Use the package manger
Did install it manually but it was still installing discord.py and pycord was not being detected ig.
Weird
Yeah but those handful of servers are too a big deal. Discord don't even backup or keep a safety system to recover those servers even if they were raided or smth
indeed
Ah, well yea. I agree, but at least not all the servers were fucked up, only a handful of those were
you got the point
I was wondering how he placed jpg in py file lol
how to make it so that only one member can use the discord_components button
and its better to use os.path and make dynamic paths when hosting
since the hosting service seems to run in a docker container
add a check...?
and better upgrade to dpy 2.0
Also either keep the same dirtree as in development or use dynamic paths, yes
Those both folder structures are completely different
^
hardcoding the paths wont work most of the times
since the directory could be located anywhere and the program could be run from any directory
@bot.command(pass_context=True)
@commands.has_permissions(administrator=True)
async def clean(ctx, limit: int):
await ctx.channel.purge(limit=limit)
await ctx.send('Cleared by {}'.format(ctx.author.mention))
await asyncio.sleep(3)
await ctx.message.delete()
It's says indentation error
But my indentation is correct
Do anyone know how to fix?
how?
Seems correct, weird
Bit still error
!pip discord_components
BTW u can use the delete_after kwarg in ctx.send to delete the message after x seconds
No prob but how to fix error
💩
i already use it
def check(inter):
return inter.author.id == command_invoker.id
await bot.wait_for("button_click", check=check)```
or use lambda
check your indents (spaces)
Anyone here have idea how to fix?
Already did
Uh tell me smth...
wait_for("button_click", check=lambda inter: inter.author.id == invoker.id)```
How would the message id be the same as user's id?
Oh author, nvm
same thing uhh my bad
💩
Nice token
try refreshing the website
@robust fulcrum
Pretty sure you copied the code
Ye
stop
it's just starting token which can be obtained by encoding user id to base64
Ok i refresh
Still
oh you copied nvm
Replit is a dumb
Bruh but replit pip is annoying
...?
I downloaded discord.py 2.0 but it changed it to 1.7
Bruh just erase the code and write it yourself
active enough to fix your typos
Actually it has a terminal
shell*
You can say
it is named as shell
Ok
And...? Pip is a standalone program for installing python packages
You can install packages in replit and it is done through pip
Yes
Imagine talking about replit
imagine hating it
Maybe I phrased it wrong, of course replit has something to do with pip, because you can use it there. But they don't mess with the source code of pip, pip was made by other people
So when something doesn't work with pip, you can't blame replit
Replit does what it's supposed to. People hate it for what it can't and shouldn't do
whats wrong with replit's pip?
Nothing
Guys how can we delete the message (cleared by ) after 3 seconds of purging
oh
people expect all kinds of things that a nomal ide does from a cloud ide, we got some high order thinking people 😔
await ctx.send(..., delete_after=seconds)```
Ok
poor hunter gets ignored
What about GitHub codespaces? I saw that you can get them for free anywhere
With the paid version you can
I mean, if u r able to pay, then why not get a VPS instead
o.o
Yeah. I once saw an organisation which let you use GitHub codespaces for free from their subscription, but forgot the name
if its replit then there pyproject.toml file has the version to use change that then
I needed to overwrite the poetry
ye
This won't work, because version 2.0 is not yet available on pypi (via pip install discord.py) You have to install it from the repository

for hosting obviously
why would someone use replit for ide unless 😳
Imagine
like someone would really go live a bot hosted with replit 
ppl do a lot actually
And then be like "why tf I receive 429 errors"
Can someone please explain to me why my bot said "ISRAEL helper 💯" as its name in dms? 💀 I got the code of a friend
exceptions in replit are like exceptions in java
just a huge mess of message without any sense
maybe nick is admin helper
Because you mentioned it
oh wait its display_name
It supports israel
Kek
@slate swan do you have members intent
yes
In java the key string is somewhere upside usually
In code?
yes
Ok show how you define intents in code
I spent last 4 days working on a project
And today the customer i'm working for decided to change the input data 
looks good to me
Ok seems valid
well then i guess i have to add if the bot is mentioned it says Admin Helper? Instead of member.display_name?
show bots profile
Btw change that construction to this
member = member or ctx.author```
More readable 😉
i cant really think of why the display_name is like that
@slate swan anyway try to print member.nick and member.name
Member can have a guild nickname, display_name will return the guild name if a guild name is set
nick will return his guild name, but it could be None
name will return the User name
Well i just added if its not in an guild it sends it like normal but it says "My avatar" and it works!
@commands.slash_command(name='test', guild_ids=config)
async def permissions(self, inter, heh):
embed = disnake.Embed
embed.title(title="Bot Permissions")
embed.set_footer('❤ Made with Love ❤')
embed.description('e')
message = await inter.channel.send(embed=embed)
time.sleep(2)
new_embed = message.embed[0] # Message.embeds returns a list, so just index the first element
new_embed.description += "UwU"
time.sleep(2)
new_embeded = message.embed[0]
new_embeded.description += f"heh"
await message.edit(embed=new_embed)
Ignoring exception in slash command 'test':
Traceback (most recent call last):
File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\slash_core.py", line 680, in invoke
await call_param_func(self.callback, inter, self.cog, **kwargs)
File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\params.py", line 817, in call_param_func
return await maybe_coroutine(safe_call, function, **kwargs)
File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\utils.py", line 580, in maybe_coroutine
return await value
File "C:\Users\Andy\PycharmProjects\WhiskeyBotMain\cogs\aboutme.py", line 36, in permissions
embed.title(title="Bot Permissions")
TypeError: 'member_descriptor' object is not callable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\interaction_bot_base.py", line 1264, in process_application_commands
await app_command.invoke(interaction)
File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\slash_core.py", line 689, in invoke
raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'member_descriptor' object is not callable
embed = disnake.Embed()
now i have
Ignoring exception in slash command 'test':
Traceback (most recent call last):
File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\slash_core.py", line 680, in invoke
await call_param_func(self.callback, inter, self.cog, **kwargs)
File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\params.py", line 817, in call_param_func
return await maybe_coroutine(safe_call, function, **kwargs)
File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\utils.py", line 580, in maybe_coroutine
return await value
File "C:\Users\Andy\PycharmProjects\WhiskeyBotMain\cogs\aboutme.py", line 36, in permissions
embed.title("Bot Permissions")
TypeError: '_EmptyEmbed' object is not callable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\interaction_bot_base.py", line 1264, in process_application_commands
await app_command.invoke(interaction)
File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\slash_core.py", line 689, in invoke
raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: '_EmptyEmbed' object is not callable
just do Embed(title=..., description=...)
ahhh. im trying to edit the description later on in code. how can i do that
embed.title(title = "") is wrong
embed.title = "title" is correct
same goes for description
message = await shit_channel.send(embed=embed)
new_embed = message.embeds[0] # I know this is counter intuitive, you could pretty much just embed.description = ... straight away
new_embed.description = "poophead
await message.edit(embed=new_embed)
shortest method
embed = ...
msg = await channel.send(embed=embed)
embed.description = "shit"
await msg.edit(embed=embed)```
Guys how can we make seprate files for every comamnd?
!d discord.ext.commands.Cog
class discord.ext.commands.Cog(*args, **kwargs)```
The base class that all cogs must inherit from.
A cog is a collection of commands, listeners, and optional state to
help group commands together. More information on them can be found on
the [Cogs](https://discordpy.readthedocs.io/en/latest/ext/commands/cogs.html#ext-commands-cogs) page.
When inheriting from this class, the options shown in [`CogMeta`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CogMeta "discord.ext.commands.CogMeta")
are equally valid here.
Is there a discord2.0?
How to make?
import motor
import discord
from webserver import keep_alive
import os
import requests
from discord.ext import commands
from discord.ext.commands import has_permissions
import urllib
import json
from motor.motor_asyncio import AsyncIOMotorClient
with open("./data.json") as file:
data = json.load(file)
cluster = AsyncIOMotorClient(data['mongo-uri'])
db = cluster["main"]
cursor = db["tutorial"]
in replit what am i supposed to put in the json file to make this work (i am refering to data.json
BlvckTvrsier, by any chance do you know why my bot cannot detect messages on threads?
Hello I have a question
threads are not supported in discord.py 1.7.3
Someone told me its because of d.py 1.7.3 but it works in 2.0 but what exactly is 2,.0?
Go ahead and ask.
its the master ( still in development ) branch of Discord.py
tou can install it using git
like for the value mongo-uri
what do i put in it
I've never installed using git. Can you tell me how to install it?
And does it include slash command, buttons and such?
Alright. Thanks!
You too @slate swan
yea, what Blvck said is correct, you need to have git installed and added to your path too
help idk what to do now
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...
!d discord.Message.add_reaction
await add_reaction(emoji, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Adds a reaction to the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji")...
!d discord.Message.remove_reaction
await remove_reaction(emoji, member)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Remove a reaction by the member from the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji")...
there you go, gl!
Can't you just do ctx.guild.leave
you can take an guild argument from the user ( discord.Guild typehint )
!d discord.Guild.leave and use this
await leave()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Leaves the guild...
then use this
Can someone help me make this ?
how do you mention guilds.....
!d discord.ext.commands.Bot.is_owner
await is_owner(user, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Checks if a [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") or [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") is the owner of
this bot.
If an [`owner_id`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.owner_id "discord.ext.commands.Bot.owner_id") is not set, it is fetched automatically
through the use of [`application_info()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.application_info "discord.ext.commands.Bot.application_info")...
their name or Id
!d discord.ext.commands.GuildConverter
class discord.ext.commands.GuildConverter(*args, **kwargs)```
Converts to a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").
The lookup strategy is as follows (in order):
1. Lookup by ID.
2. Lookup by name. (There is no disambiguation for Guilds with multiple matching names)...
this Exists
hey guys how do you ref a json file in replit
Yes
The same way u do in yr PC
so like this?
with open("./data.json","r") as f:
users = json.load(f)
Sure
if the file is in the same directory, yes
root directory*
oh
root directory doesn't take a "./" you can simply use data.json in that case
depends on ur file structure tbh
heh? no?
why does it work for me
Guys anyone here know how can we make a command that a user can use only once in 12 hours like vote command
!d discord.ext.commands.cooldown
@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
A cooldown allows a command to only be used a specific amount
of times in a specific time frame. These cooldowns can be based
either on a per-guild, per-channel, per-user, per-role or global basis.
Denoted by the third argument of `type` which must be of enum
type [`BucketType`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType")...
Hi Ash
Like i used comamnd and i got 12 hours cooldown . Will other uses able to use it?
Read the docs... it explains how it works
I'm using Disnake how can I add a field to a embed
!d disnake.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.
why does the balance not increase at all:
async def open_acccount(user):
users = await get_bank_data()
if str(user.id) in users:
return False
else:
users[str(user.id)] = {}
users[str(user.id)]["wallet"] = 0
users[str(user.id)]["bank"] = 0
with open("./data.json","w") as f:
json.dump(users, f)
return True
async def get_bank_data():
with open("./data.json","r") as f:
users = json.load(f)
return users
client.command()
@commands.cooldown(1,15,commands.BucketType.user)
async def beg(ctx):
await open_acccount(ctx.author)
users = await get_bank_data()
user = ctx.author
earnings = random.randint(0,100)
mbed = discord.Embed(
title="You beg other monkes for monkeybux...",
description=f"and get {earnings} monkeybux!"
)
await ctx.channel.send(embed=mbed)
users[str(user.id)]["wallet"] += earnings
wait ill read that
if your gonna tell me there is no
os.chdir("path")
it was done in replit
this is the problem
Hi, i would like to acces to my rsp pi (with linux) and control it via a discord bot, do you think it could be possible?
so in beg how do i not make the return 0
everything is posible
i think if you save it in sql better
but was wondering wich lib could i use to connect and execute some commands on my rsp pi
idk how to use sql with discord.py
so my best bet was json
when u get more monkeycoin it saves in json file or not
no
nothing happens to json
{"user": {"wallet": 0, "bank": 0}, "user": {"wallet": 0, "bank": 0}, "user": {"wallet": 0, "bank": 0}}
user is the user id
thats the json file after begging (3 ppl used the command)
👃 I smell dank memer clones 
just use sqlite and its async driver
Umm is there a user ID actually in the Json or just "user"
its userid
just did not share it
Ok... that's why I was asking lol
PostgreSQL sad noises

Does anyone knows a professional discord.py developer?
theres no professional dpy dev lmao
this isnt a profession
i think you ment experienced?
Haha I am making it a profession with my business
Yep that’s a better way to put it
👀
in replit how to do that
I have a big project in development if you have any specific recommendations
uh...you're better than me like a thousand times
no
ash youre the best 🙏
and your looking for recommendations on abstractions?
why am I always the center of embarrassment
omg😭
Yeh I’m ideally looking for someone to join a team as a full time python dev
ah cool
Yeh if you know anyone who would be interested pls lmk 😊
i think i found the issue
async def open_acccount(user):
users = await get_bank_data()
if str(user.id) in users:
return False
else:
users[str(user.id)] = {}
users[str(user.id)]["wallet"] = 0
users[str(user.id)]["bank"] = 0
for someone reason the if condition is false
then the values get reseted to 0
i mean im down ig i havent done anything in like a week and i havent encountered problems with my best package pykawaii
Amazing! Can I dm you?
send me a friend request i have my dms locked lol
Perfect! Sent
👍
for what?
u can do return await and u don't need an else statement after that since it returns anyway
k
@shrewd apex so... can we dm?
It is a cross server discord bot build mainly for NFT servers
async def open_acccount(user):
users = await get_bank_data()
if str(user.id) in users:
return False
users[str(user.id)] = {}
users[str(user.id)]["wallet"] = 0
users[str(user.id)]["bank"] = 0
with open("./data.json","w") as f:
json.dump(users, f)
return True
async def get_bank_data():
with open("./data.json","r") as f:
users = json.load(f)
return users
it returns true
when the condition is false
so return await?
no i can answer questions i don't give guides
u can remove the indent
as i said u don't need the else u can remove that and stick everything to the side
rest will work as it is return True is not particularly required either
ehmm... k.... I don't know nothing about phyton, or programming in general... do you know were to start to create a bot that combines dyno's moderation and mee6? @shrewd apex
also i wouldn't use json in cases for storing and frequent usage of data i would use sql i personally use postgres
i dont really know how to use sql with replit
idk abt using replit so can't comment on that u can try mongodb tho it's pretty similar to jsons
how i do that
that text
wn.onkey(lambda: t1.setheading(180), 'Left')
wn.onkey(lambda: t1.setheading(0), 'Right')
"wn.onkey(lambda: t1.setheading(180), 'Left')
wn.onkey(lambda: t1.setheading(0), 'Right')"
no
if u are a absolute beginner watch yt tutorials and learn python basics
like
yes
"'wn.onkey(lambda: t1.setheading(180), 'Left')
wn.onkey(lambda: t1.setheading(0), 'Right')'"
'''wn.onkey(lambda: t1.setheading(180), 'Left')
wn.onkey(lambda: t1.setheading(0), 'Right')'''
wn.onkey(lambda: t1.setheading(0), 'Right')```
put py
YAY!
after the three
lmao u used only 1 `
wn.onkey(lambda: t1.setheading(180), 'Left')
wn.onkey(lambda: t1.setheading(0), 'Right')```
YOOOOOO
ty
@shrewd apex
will this work
async def update_bank_data(user,change = 0,mode = "wallet"):
users = await get_bank_data()
users[str(user.id)][mode] += change
with open("./data.json","w") as f:
json.dump(users, f)
bal = [users[str(user.id)]["wallet"],users[str(user.id)]["bank"]]
return bal
i wil call it to update the balance
.
Json database 🥲
Use a global check
@bot.check
async def global_check(ctx: commands.Context):
return ctx.guild.id == your_guild_id```
ok ty
class discord.Role```
Represents a Discord role in a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild")...
why does this return this error when in a Voice channel?
Command raised an exception: AttributeError: 'int' object has no attribute 'isnumeric'
when I am not connected it returns this error:
Command raised an exception: AttributeError: 'NoneType' object has no attribute 'channel'
code:
@bot.command()
async def roulette(ctx):
VoiceID = ctx.author.voice.channel.id
voicemembers = nextcord.VoiceChannel.members
if VoiceID.isnumeric():
shuffeledvms = random.shuffle(voicemembers)
randvm = random.choice(shuffeledvms)
shuffeledvms.move_to(None)
else:
await ctx.send("You need to be in a voice channel!")
all I needed to know thanks
Can someone help me make this ?
You need to find out some things yourself
We're not going to code something on demand bro
but ill send u something
Do me a favour and read what is demand
?
And u don’t have to answer , I have people who don’t mind answering
!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.
you gotta utilise the discord.ui.View class and use View.add_item(discord.ui.Button(**kwargs))
great, then go for it
class MyView(discord.ui.View):
@discord.ui.button(label="action1", **kwargs)
async def action1_callback(self, interaction: discord.Interaction ,button: discord.Button) -> None:
...
# action to do upon clicking
``` this should make it clear.
This what I showed is a trivia system , which means I need certain packages and a difficulty , for example trivia easy , trivia medium , trivia hard
That’s my main problem
alright makes your question way better tounderstand
Ok
have u brainstormed already on how you could basically do it?
don't tell me you watched a YT video about this
wish there was a ?tag lucas unban here
equally as bad mostly
this sucks
ctrl +f unban in this channel
this has been solved many times before
async for ... in bans(*, limit=1000, before=..., after=...)```
Retrieves an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") of the users that are banned from the guild as a [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry "discord.BanEntry").
You must have the [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission
to get this information.
Changed in version 2.0: Due to a breaking change in Discord’s API, this now returns a paginated iterator instead of a list...
Is your unban command looking like this?
for ban_entry in banned_users:
user = ban_entry.banned_users
if (user.name, user.discriminator) == (member_name, member_discriminator):
...
Lucas' unban only works for banning people via their name#discrim, now, this way is not wrong, but there are easier ways of unbanning people, e.g.:
# Unbanning by ID only (converting the ID to a object using discord.Object):
await ctx.guild.unban(discord.Object(id = id))
# converting the given user to a User object by type hinting:
async def unbean(ctx, user : discord.User, reason = None):
Inspiration from d.py official server
also, this ^
how to delete bot's message after button click?
🍿
Can you edit other users messgae to add spoilers to it?
depends on which message
you cant
nop
bw guys how can i fix this py winner = random.choice(users) File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\random.py", line 378, in choice return seq[self._randbelow(len(seq))] IndexError: list index out of range
index the list within its max index
because it doesnt exist
so ..?
I want the bot message to be deleted when the red button is clicked
so how do i fix it where do i index the list
wait photo
!e
c = [1, 2, 4, 5, 6]
print(c[69])
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | IndexError: list index out of range
questionList =[
["What channel should it be in?", "Mention the channel"],
["How long should this giveaway last?", "d|h|m|s"],
["What are you giving away?", "E.G. Pizza"]
]
answers = {}``` this ?
doesnt work
store the message in an var and use the delete method in it
msg = await ctx.send(...)
//wait for the button click maybe
await msg.delete()
yes
yes
questionList =[
["What channel should it be in?", "Mention the channel"],
["How long should this giveaway last?", "d|h|m|s"],
["What are you giving away?", "E.G. Pizza"]
]
answers = {}``` this ?
?
where do i index
love your examples😭
random.choice is causing the error
uhm....thanks
winner = random.choice(users)``` so what now

thx, it is working
what is wrong with this variable?
VoiceID = ctx.author.voice.channel.id
it returns this:
Command raised an exception: AttributeError: 'NoneType' object has no attribute 'channel'
winner = random.choice(users)``` can someone tell me how do i fix this
ah lemme search on google
is users just 1 object?
users is empty
it will still return that 1 object
ill just send code
voice is None
!d discord.Member.voice
property voice```
Returns the member’s current voice state.
idk why people donteventryto understandtheerror that is caused by theircode
https://paste.pythondiscord.com/kirodenace here is my code
i love your point but that wording is just😭
lmao, my bad, my english aint the best 😔
i see that😭
no offence but for a second you really made me feel like - "what am I even writing...is that even english", ngl
😔
so does anyone know how to fix my code , its multiguild
im sorry😔
It means the user isn’t in a voice channel
Robin is so smort
no, bye
am i muted or something , brb
ill just explain in messages.
giveaway.py has been loaded
Ignoring exception in command giveaway:
Traceback (most recent call last):
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\Dom\Desktop\beta test\cogs\giveaway.py", line 104, in giveaway
winner = random.choice(users)
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\random.py", line 378, in choice
return seq[self._randbelow(len(seq))]
IndexError: list index out of range``` this is my error , how do i fix it
yo robin can u help me
I can try
ok
Well the error is self explanatory is it not
😔
Only cause of the error might be that user is empty
try:
reaction, member = await self.client.wait_for(
"reaction_add",
timeout=60,
check=lambda reaction, user: user == ctx.author
and reaction.message.channel == ctx.channel``` i have this
ofc 🧠
@slate swan
In your on message, check if the message.content == bot.user.mention
If so, send something
Pretty sure you aren’t included in the reactions in the first place
Try printing it out to be sure
https://paste.pythondiscord.com/kirodenace can u check this
Yeah, try printing the list of reactions
try:
reaction, member = await self.client.wait_for(
"reaction_add",
timeout=60,
check=lambda reaction, user: user == ctx.author
and reaction.message.channel == ctx.channel
)
print(reaction)``` like this?
doesnt work
How to set this type of slash command in the nextcord?
[<Member id=975835075784617994 name='Beta Testing' discriminator='9566' bot=True nick='FROZENFUT LEVEL SYSTEM' guild=<Guild id=942487587602456617 name='FrozenFut' shard_id=None chunked=True member_count=8104>>, <Member id=944343972258648115 name='MasterKnots' discriminator='9999' bot=False nick=None guild=<Guild id=942487587602456617 name='FrozenFut' shard_id=None chunked=True member_count=8104>>]
[<Member id=975835075784617994 name='Beta Testing' discriminator='9566' bot=True nick=None guild=<Guild id=975835154029355029 name='Beta Testing Support' shard_id=None chunked=True member_count=20>>, <Member id=944343972258648115 name='MasterKnots' discriminator='9999' bot=False nick=None guild=<Guild id=975835154029355029 name='Beta Testing Support' shard_id=None chunked=True member_count=20>>]``` guys this showed up , is this bad?
@bot.command()
async def roulette(ctx):
try:
VoiceID = ctx.author.voice.channel.id
vms = []
voicemembers = nextcord.VoiceChannel.members
vms.append(voicemembers)
print(vms) # print is for debug reasons
if len(vms) <= 0:
return
elif len(vms) == 1:
await ctx.send("Bro...You are alone why would you want to play Russian roulette by yourself?\nGo get a friend!")
else:
VoiceID = ctx.author.voice.channel.id
randvm = random.choice(vms)
randvm.move_to(None)
except:
await ctx.send("You need to join a Voicechannel!")
There are 2 users in the Voice Channel.
Why doesn't it add both members to the list?
@slate swan i think it logged it idk
yep it logs the users now
you need an instance of VoiceChannel
oooooohh
not nextcord.VoiceChannel.members. you can get it with ctx.author.voice.channel.members
well now the list is completly empy
no
thats just a list of member objects
its formatted like that because of the Member class's __repr__
show updated code. also len(vms) will always be 1 because you are adding the list of members to the list vms
@bot.command()
async def roulette(ctx):
try:
VoiceID = ctx.author.voice.channel.id
vms = []
voicemembers = ctx.author.voice.channel.members
vms.append(voicemembers)
print(voicemembers)
if len(vms) <= 0:
return
elif len(vms) == 1:
await ctx.send("Bro...You are alone why would you want to play Russian roulette by yourself?\nGo get a friend!")
else:
VoiceID = ctx.author.voice.channel.id
randvm = random.choice(vms)
randvm.move_to(None)
except:
await ctx.send("You need to join a Voicechannel!")
lemme remove vms
yeah you should just use voicemembers
everything works except no ones is getting kicked since the list is still empy
hmm im not sure why the list is empty
neither am I
@bot.command()
async def roulette(ctx):
try:
VoiceID = ctx.author.voice.channel.id
voicemembers = ctx.author.voice.channel.members
print(voicemembers)
if len(voicemembers) <= 0:
"List is empty"
elif len(voicemembers) == 1:
await ctx.send("Bro...You are alone why would you want to play Russian roulette by yourself?\nGo get a friend!")
else:
randvm = random.choice(voicemembers)
randvm.move_to(None)
except:
await ctx.send("You need to join a Voicechannel!")
code rn
i think I know why
u always need to add await b4 ctx right?
nvm
forget waht I said
Hello, Coders!
How to make localization to slash commands? I am usin' nextcord, but I can switch to smth else (except discord.py and pycord)
green, primary is blue
This is just an idea
import ButtonStyle
so how do u use it?
can you send me some screenshots
from discord import ButtonStyle
@slate swan
!d discord.ButtonStyle
class discord.ButtonStyle```
Represents the style of the button component.
New in version 2.0.
^
i wonder why that class isnt limited to the ui folder
same thought but the question is automatically answered when you remember that you're talking about discord.py
😭
how to do this in python
someone will send a message and reply to him on the bot but without prefix
@client.event
async def on_message_edit(before,after):
channel=client.get_channel()
embed=discord.Embed(color=0x123456)
embed.set_author(name=f"{before.member.name}", icon_url=before.member.name.avatar_url)
embed.add_field(name=f"Előtte",value=f"{before.content}", inline=True)
embed.add_field(name=f"Utána",value=f"{after.content}", inline=True)
await channel.send(embed=embed)
AttributeError: 'Message' object has no attribute 'member'
is it for me?
nope
./
.
it's before.author
also, what formatting is this
ty
and why do you use these f-strings 😭
i love it
yap
ty its work
and how can i mention the channel where edited this message with the after/before
fixed
!d discord.on_message
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled...
@commands.command()
async def slowmode(ctx,time:int):
if (not ctx.author.has_permissions.manage_messages):
await ctx.send('This command requires ``Manage Messages``')
return
try:
if time == 0:
await ctx.send('Slowmode turned off')
await ctx.channel.edit(slowmode_delay = 0)
elif time > 21600:
await ctx.send('You cannot set the slowmode above 6 hours!')
return
else:
await ctx.edit(slowmode_delay = time)
await ctx.send(f'Slowmode set to {time} seconds!')
except Exception:
await print('Hmmmm..')```
if (not ctx.author.has_permissions.manage_messages):
AttributeError: 'slowmode' object has no attribute 'author'```
anyone have way to import all cogs automaticly without importing one by one
Can you tell me how to calculate the list coin = ['COIN', 'ASCOIN'] and if the user enters the command .coin COIN it checks if there is an intersection point after .coin in the list and outputs either a runtime error actions
it involves getting file list with os.lisdir(directory) and checking if file name ends with .py
what's wrong with adding cogs manually?
wait, you mean loading extensions, right?
@heavy shard
can u tell me whats wrong with this code
@commands.command()
async def slowmode(ctx,time:int):
if (not ctx.author.has_permissions.manage_messages):
await ctx.send('This command requires ``Manage Messages``')
return
try:
if time == 0:
await ctx.send('Slowmode turned off')
await ctx.channel.edit(slowmode_delay = 0)
elif time > 21600:
await ctx.send('You cannot set the slowmode above 6 hours!')
return
else:
await ctx.edit(slowmode_delay = time)
await ctx.send(f'Slowmode set to {time} seconds!')
except Exception:
await print('Hmmmm..')```
i noticed something annoying about discord ||for android||
whats that
if the command is part of commands.Cog, it needs first argument self
the time thing doesnt tick down -.-
lemme show error
<t:1234567890:R>
says "13 years ago" here
File "C:\Users\Dom\Desktop\beta test\cogs\slowmode.py", line 11, in slowmode
if (not ctx.author.has_permissions.manage_messages):
AttributeError: 'slowmode' object has no attribute 'author'```
13 years ago
|| hello ||
i'm guessing "slowmode" is name of the commands.Cog class you made
<t:1653681340:R>
there we go
and the error says something like ctx is slowmode class, which means you skipped/forgot first argument, which is self
on android it's just stuck lol
so what do i do
async def slowmode(self,ctx,time:int):
👋 <t:1653681640:R>
i wish there was a precise timestamp that said something like "2 years, 45 days, 5 hours, 2 minutes ago"
yeah that would be sick
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'has_permissions'``` next error
what i was doing is sending a message with a timestamp tag of X seconds in the future and delete_after=X
then the code does asyncio.sleep(X) and then sends whatever
you should rather try channel.permissions_for( discord.Member )
if not ctx.author.guild_permissions.manage_messages:
because the API i use has a estimated_time in responses when its not yet ready
wdym
i thought of using a task to edit the message every second but that seemed like too much work
ctx.channel.permissions_for(ctx.author).manage_messages
is it commands.has_permissions ?
can i do while in while?
but it would work for every command
thats not how they want to do it ?
I don't think so
can you nest while -s? of course
you just cant continue or break the outer loops from the inner loop which is a bit lacking
@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member has all of
the permissions necessary.
Note that this check operates on the current channel permissions, not the
guild wide permissions.
The permissions passed in must be exactly like the properties shown under
[`discord.Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions")...
because its a component of messages and it makes no sense for it to be inside the ui constructor folder, "making" buttons is not the only usecase
!d discord.ext.commands.MissingPermissions.missing_permissions he could even handle it and get the same results
The required permissions that are missing.
and he wouldn't have to do the same for every command
the class is for the style of a component(button) which the component is a button for a ui
the ui folder includes only classes that are used to "make" components, there are no read only classes.
File "c:\Users\gramo\OneDrive\Робочий стіл\Bot\server.py", line 156, in report
await reportchannel.set_permissions(roleforum, delete_messages = True)
File "C:\Program Files\Python310\lib\site-packages\discord\abc.py", line 648, in set_permissions
raise InvalidArgument('target parameter must be either Member or Role')
discord.errors.InvalidArgument: target parameter must be either Member or Role
no role with that ID exists, or you dont have role intents
which you need the buttons actual style to make it?
thats just an enum class.
ButtonStyles are literally just numbers
thats like having Intents inside the client.py since you need them for making it
what?
you make no sense? im literally having a stroke trying to comprehend your point.
thats why you should check the complete file paths and all the places where that class has been used before making a comment on the library
!d discord.ui.Button.style
property style```
The style of the button.
so you want it to return a discord.ui.ButtonStyle?
well it seems like you didnt quite read my comment🤔
i wonder why that class isnt limited to the ui folder (edited)
"limited"
elaborate what do you mean by limited?
its namespace
so you mean it should be discord.ui.ButtonStyle?
limited to that namespace? that is so.
iwonder why the slash commands dont show up
no more
when i tried bot.slash_commands i got this ['invite', 'bump', 'remove', 'add', 'help', 'botinfo', 'preview', 'setup', 'unload', 'check', 'vote'] but
- it used to work fine idek why it doesnt work no more
so you want an enum to not be in enum.py and in the ui folder instead, makes sense xd
just have an enum file for each folder? so each enum is set to its category where it falls in?
😂
any idea
did you reload your client?
ye
whats so funny?
a file, for a single class? the enum for which is not just being used in that folder but the root folder too, why?
there's a discord.Button class, which uses that enum too, and no it does not lie inside the ui folder
thats like having a banana in the vegetables drawer
so you would be py from .ui.enums import ButtonStyle instead of py from .enums import ButtonStyle not fair
that doesnt make any sense in this context
exactly thats my point.
well, im too unqualified to explain this, try discussing it with someone who actually helped in designing the libary
but in my opinion, the abstraction is perfect.
🤷♂️
btw, look into the source code, they use discord.Button ( components.py) to make discord.ui.Button(ui/buttons.py) 😂 lets blame them for this too.
smh
thats what i was saying for the time being. they derive the constructor classed from base classes
so keeping the enum limited to the ui folder wont make any sense
the component.py file shouldnt even be in the parent folder it should be in the ui folder
again, ask them not me lmao
i wasnt asking you tho
they use that in messages.py
Sheshead.
polls maybe
Hey!
I need some more help with a bot
different bot
For some reason this ranking bot doesn't work that I made; also I don't know how you would add a command to get your level and a leaderboard of the top 10 highest leveled people.
Here is the script.
from discord.ext import commands
import json
import discord
import os
import random
import time
client = commands.Bot(command_prefix = "!")
#On Ready Event.
@client.event
async def on_ready():
print("Bot Ready.")
time.sleep(1)
print("Logged In As: {0.user}".format(client))
#Function For Getting A Users Information And Level Them Up.
@client.event
async def on_member_join(member):
with open("users.json", "r") as f:
users = json.load(f)
await update_data(users, member)
with open("users.json", "w") as f:
json.dump(users, f)
#Function For Sending Messages.
@client.event
async def on_message(message):
with open("users.json", "r") as f:
users = json.load(f)
#amount_of_experience = float(randint(1, 5))
await update_data(users, message.author)
await add_experience(users, message.author, 5)
await level_up(users, message.author, message.channel)
with open("users.json", "w") as f:
json.dump(users, f)
async def update_data(users, user):
if not user.id in users:
users[user.id] = {}
users[user.id]["experience"] = 0
users[user.id]["level"] = 1
async def add_experience(users, user, exprience):
users[user.id]["experience"] += exprience
async def level_up(users, user, channel):
experience = users[user.id]["experience"]
level_start = users[user.id]["level"]
level_end = int(experience ** (1/4))
if level_start < level_end:
await client.send_message(channel, f"{user.mention} Has Leveled Up! They Have Leveled Up To Level {level_end}!")
users[user.id]["level"] = level_end
#Commands !level (Gets Level), And !leaderboard (Gets The Top 10 Highest Leveled People In The Server).
#Stop Being Able To Level Up And Get Experience When Doing Commands Or Spamming.
client.run(os.getenv("Token"))
client.run(os.environ["Token"])```
But, for some reason the JSON File doesn't update and no message is sent at all.
Please help.
Member.id returns an int, you can't have an integer as an index in a JSON file, try str(user.id) instead of user.id
Okay I'll try that.
for await ctx.guild.bans() remove the await
!d discord.Guild.bans
guild.bans() returns an async iterator
async for ... in bans(*, limit=1000, before=..., after=...)```
Retrieves an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") of the users that are banned from the guild as a [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry "discord.BanEntry").
You must have the [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission
to get this information.
Changed in version 2.0: Due to a breaking change in Discord’s API, this now returns a paginated iterator instead of a list...
never mind, mb
Just you still don't level up or get a level up message oddly enough.
you're right, but that's in v2
It says Bot has no attribute send_message, how do I get around this @fading marlin.
read the docs that Sniper sent
you'll have to do some other shit
specifically
async for ban_entry in ctx.guild.bans():
don't watch 3 y/o tutorials on youtube. Pass in message.channel to your level_up function, and replace client.send_message with channel.send to send the message
how to make button (discord_components) clickable only for ctx.author?
Okay, thanks for the advice, lol I'll do that rn
It works now, ty dude!
By any chance would you know how to loop through a JSON File and get the top 10 highest levels and put it into a command?
you're basically referring to you using json as a database
which is NOT its intended use
TypeError: eightball.eightball() takes 1 positional argument but 2 were given
guys how can i fix this
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.
also, for future reference, don't do that ever again: just sending one line with the error
https://www.youtube.com/watch?v=SxNnB5GKj_k
Gemaakt door Freek Galloo / Aäron Lepers
you didn't add self as first arg in the method of your class
Ok works
oh okay! ty
Oh I see, so will it bug out?
But there must be a way!
This is really the only option for me.
like what?
aiosqlite or asyncpg
how would I switch everything from it.
you'll need to learn SQL first
#databases
When writing an SQL schema, the important thing to remember is you have a limited number of columns and tables, but unlimited rows.
So, for the following json document design
{
user_id:{
money:int,
name:str,
inventory:
[
{
item\_name:str
description:str
count:int
}
]
}
}
we would create three tables:
a user_info table:
user_id INTEGER, name TEXT, money INTEGER\
an item_info table:
item_id INTEGER, name TEXT, description TEXT
and a user_inventory table:
item_id INTEGER, user_id INTEGER, count INTEGER
Further, user_inventory's item_id and user_id would be foreign keys referncing item_info and user_info.
item_id could be set to autoincrement as well.
The schema is avaliable here: https://paste.sr.ht/~vex/84d3be4b80eb7a062651cf2f8acb4046087b9031
But, why? Why would you expand this all to three tables?
Well, a number of things- firstly, we're not creating a bunch of duplicate data- for the above json document, if two users had the same item, we would need to copy the whole item document. In this schema, we just reference an individual row with that data. Further, because of our usage
of foregin keys, if we delete an item from item_info, it propigates to every single user's inventory and is removed- or, if a user is
removed, their inventory entry is cleared as well.
To retreive values, we would join the tables on each other. For example, to retreive the inventory of a user with ID 1234, we could do the following query:
SELECT item_info.item_name,
user_inventory.count
FROM user_inventory
INNER JOIN item_info
USING(item_id)
WHERE user_inventory.user_id = 1234 ```
To add an item to a user's inventory using an item name by their ID, we could do the following:
```sql
INSERT INTO user_inventory
VALUES (1234,
(SELECT item_id
FROM item_info
WHERE item_name = "pills"),
1) ```
=> stolen from discord py help server
oh, damn, okay
But just the basics right?
sure, CRUD operations
Wow, okay. Got it.
if im using await view3.wait() how can i make it wait for 1 second
lol, wait what's the invite link for that?
view3 is a button view
Tell me if I'm wrong but is SQL a language, and is this in SQL?
k, tysm
yup
SQL is the language databases use
I see.
I understand; it must be a very useful tool in the grand scheme of things then
have you checked the docs?
can u link
ofc, it's called a DATABASE for a reason
yeah, lol
don't tell me you've been learing to code bots through video's?
no
like link the docs
well, just look for the wait method
it might have a kwarg with a timeout or whatever
I don't use v2, so can't say
How do I create a subcommand in discord.py? Im using slash commands btw
Set the timeout = 1 and view.wait() returns True if it gets timed out
how to make button (discord_components) clickable only for ctx.author?
!d discord.ui.View.wait
await wait()```
Waits until the view has finished interacting.
A view is considered finished when [`stop()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View.stop "discord.ui.View.stop") is called
or it times out.
me?
No its for ^
ok
ok
help meeeeeee
pls
timeout = 1 in the view or
class discord.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
oh thanks
Check if interaction came from author. If no, don't respond them
Not sure if buttons can be enabled/disabled into discord ui for a particular user
!e
code
yeah, maybe the bot is private anyway
I don't use nextcord so im not able to help, sorry
its the same thing
just 4 letters are diffrent
huh
If u want to I can just migrate it to discord.py
Is this a slash command?
what?
no there shouldnt be a slash command if u mean that
I'm pretty sure it's a regular command, it should be just ctx.send() not ctx.send_message()
send_message is a InteractionResponse.
Please provide the traceback.
only the bot.event works
thats also a problem, there is non
it just doesnt work
Oh you are using on_message commands
I recommend just removing the on_message event.
its the only thing that works
litearlly
Yeah that's what I'm trying to say.
If you do want to keep the on_message event put await bot.process_commands(message) at the end of the event.
Since the Bot extension also is just an on_message you overridden the commands.
You can also make on_message a listener to avoid this.
Would anyone know how to make it so that if a user spams they won't get Experience and Level Up other wise they will. This is in a Leveling Bot that I'm working on, please try to help if you can.
!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.
you can make a custom cooldown for those on_message s
Hi So I have this task loop py @loop(minutes=5) async def afk_check(self): print("Afk check loop triggered.") puffcord = self.bot.get_guild(self.bot.config.default_server) log_channel = puffcord.get_channel(self.log_channel) embed = Embed(colour=Colour.dark_orange(), timestamp=datetime.now()) embed.set_author(name="AFK Members") for member in puffcord.afk_channel.members: print(f"{member.name} is in the afk channel.") if member.id not in self.akf_members: self.akf_members[member.id] = datetime.now() print(f"{Member} is not in the afk_members dict, adding them.") if member.id in self.akf_members.keys(): print(f"{Member.name} is in the afk_members dict, checking time.") if (datetime.now() - self.akf_members[member.id]) > timedelta( minutes=self.allowed_time ): print("Passed time comparison") self.count += 1 while len(self.akf_members) >= 1 and len(embed.fields) < 24: print(f"Adding {member} to embed") embed.add_field( name=f"{member.name}#{member.discriminator}", value=f"{member.id}", inline=False, ) del self.akf_members[member.id] which gets to ```py
print(f"Adding {member} to embed")
2022-05-27T22:40:03: Adding SnowyJaguar#1034 to embed
actually I think I found the error ```py
2022-05-27T22:40:03: Unhandled exception in internal background task 'afk_check'.
2022-05-27T22:40:03: Traceback (most recent call last):
2022-05-27T22:40:03: File "/usr/local/lib/python3.8/dist-packages/discord/ext/tasks/init.py", line 101, in _loop
2022-05-27T22:40:03: await self.coro(*args, **kwargs)
2022-05-27T22:40:03: File "/home/testing/cogs/afk_manager.py", line 89, in afk_check
2022-05-27T22:40:03: del self.akf_members[member.id]
2022-05-27T22:40:03: KeyError: 365262543872327681
ty
But, I want to not give them levels and experience, not stop them altogether, how would I do that?
Could you show how akf_members is defined?
instead of doing that action which is sending the message, you can just return there
oh okay, I see, ty then
# In cog init
self.akf_members = {} # member ID : time
# In voice state event
self.akf_members[member.id] = datetime.now()
# What my logs show when i print the dict
2022-05-27T22:43:55: {791441599997018133: datetime.datetime(2022, 5, 27, 23, 35, 3, 895812)}
```full code: https://paste.pythondiscord.com/adukovuyur
Who is 791441599997018133
one of my alts, which now I realise wasn't removed from the dict so that makes sense. Now it's odd that it says it added me to the embed twice when it hasn't done it once
okay I'll try that
for legal reasons this is a joke and not even mine
But yeah its not very "cool" ik
@wet crystal Don't post code containing such content here in the future please.
Can python make a bot like dyno?🙂🙂I am new
I did 
Yes, it can, it can do anything that js can but dyno also works with its own api and database so you would need to go over the discord.py edge
e.g mee6 is made in python which mee6 is one of the most popular bots in discord so i wouldnt underestimate python 😉
dank memer isnt in this server lol
Anyone know if there is any bot who russian roulettes and kicks a random guy from the call?
its quite easy just check if the Context author is in the mentioned voice channel and then use the random module and just remove the user
It probably wouldn't be too difficult to write that yourself. Essentially you need to get the IDs of the users in the voice channel, select one with random.choice, then kick that person from the channel.
What about blanks?
What do you mean?
Russian Roulette isnt just having a random one losing instantly but also to have somewhen, where nothing happens, these ate called böanks
Hoe could you integrate a 5/6 chance to have a blann
Something like if random.random() < 5/6: ...
random.random() is a random number between 0 and 1.
or a counter randomly initialised to number from 1 to 6, decreasing every try, and triggering on 0
depends on the implementation
You could also use randint(1, 6) anything other than 1 being a blank
is there any current build overrides for making slash commadns visually better?
can you get an ID from a name, like 944202890015277106 from 𝔃𝓱#1209?
Not directly
how can i verify if the user is the bot owner?
You can get an id from a user object
ik
how do you get it from name tho
copy the owners id into the code as a constant
Do you know in which guild the user is?
wym
the bot will be in the same guild if thats what you mean
Ah okay
This is how you would get the member matching name and discriminator (the number after #)
member = discord.utils.get(guild.members, name="name", discriminator="1234")```
discord.utils has some other handy functions too, here are the docs: https://discordpy.readthedocs.io/en/latest/api.html?highlight=find#utility-functions (v2.0)
!d discord.ext.commands.MemberConverter be like
class discord.ext.commands.MemberConverter(*args, **kwargs)```
Converts to a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member").
All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.
The lookup strategy is as follows (in order)...
Could someone help me creating a subcommand? Im using slash commands with discord.py
do you have any code currently
No
They are rare for us people anyways
They are mainly made for Discord Devs to test the stuff out without repeatedly updating and degrading their client
ive cut this down massively to simplify this, but does anyone know why this isnt firing off when i send a msg? (context in second code box)
if msg.content.lower() in ctx.bot.game_states[str(game_channel.id)].valid_game_options:
if not ctx.bot.game_states[str(game_channel.id)].begun:
await game_channel.send("**Act One, Scene One: The Beginning**")
class NewGameState:
valid_game_options = []
# the game_channel.id part is customised, but i can confirm it works.
ctx.bot.game_states[str(game_channel.id)] = NewGameState()
ctx.bot.game_states[str(game_channel.id)].valid_game_options = ['ready', 'play', 'start']
if msg.content.lower() in ctx.bot.game_states[str(game_channel.id)].valid_game_options:
if not ctx.bot.game_states[str(game_channel.id)].begun:
await game_channel.send("**Act One, Scene One: The Beginning**")
ctx.bot.game_states[str(game_channel.id)].begun = True # Starts the game
Have you tried printing
print( ctx.bot.game_states[str(game_channel.id)].valid_game_options )
```?
That might clue you in as to what's going on
i mean i know the valid_game_options is correct because
while ctx.bot.game_states[str(game_channel.id)].game_over:
await game_channel.send(content=f'When ready to play, type any one of the following: {options_string}')
again simplified, but it prints out the string
What do you mean by "correct"? What values does it hold?
it should be
ctx.bot.game_states[str(game_channel.id)].valid_game_options = ['ready', 'play', 'start']
and it prints those 3 options
it just doesnt seem to pick up on inputs
Okay, and you don't reassign any values? It's just a static list?
the values can be changed; if i pm u the pastebin link for the entire thing so u got context would that help?
Yes please, paste the link here though
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
theres a considerable amount, so i tried to cut down on what was irrelevant to the issues im having rn
@sick birch
Cool, just scanned it. To be clear, the issue is that it won't send the message Act One, Scene One: The Beginning?
yes, as everything else comes after that anyways
until i can get it to accept inputs in the channel i cant go forward with any other parts of the 'story' code anyways
Can you try printing ctx.bot.game_states[str(game_channel.id)].begun?
print(ctx.bot.game_states[str(game_channel.id)].begun)
So like
if msg.content.lower() in ctx.bot.game_states[str(game_channel.id)].valid_game_options:
print(ctx.bot.game_states[str(game_channel.id)].begun)
if not ctx.bot.game_states[str(game_channel.id)].begun:
ok
It can A) not print anything at all or B) print False
yeah printed nothin
In that case, can you try this
print(msg.content.lower() in ctx.bot.game_states[str(game_channel.id)].valid_game_options)
```?
If it doesn't print anything again it should be an easy fix
where soz?
print(msg.content.lower() in ctx.bot.game_states[str(game_channel.id)].valid_game_options)
if msg.content.lower() in ctx.bot.game_states[str(game_channel.id)].valid_game_options:
if not ctx.bot.game_states[str(game_channel.id)].begun:
there?
what does inline mean in discord.Embed.add_field ?
Yes
yeah still nothin
If inline=True, multiple name/value pairs can be printed on a single line (think one row)
!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.
so it just adds the \n for you
kinda useless
intents r set to all in the bot code tho, as well as in the dev portal
r u saying its able to read text commands but not plain text inputs ?
You have intents.message_content=True?
Not really
how can i implement a bot owner only command
It's placed in different spots on discord
there is a tiny difference in the gap size
i need the @ for the owner only
Which cannot be accomplished using \n, yes
but like 3 pixels at most
And if it's side by side it's more of a grid layout
that isnt in the code no
with columns properly aligned?
Well, you need that for message intents
Discord tries its best to align it properly with the content you have
Not guaranteed though
sheesh i might try that then
on mobile phones, its always inline=False
that shows nothing
It shows exactly how the whole thing works
no
The first 2 fields have inline=True passed, the last 2 have inline=False
thats all it does 🙂
maybe try reading the embed field names.
there is only 1 set of inline ones
if there was 2 sets with different length strings it would show it
If you set all 4 of them to inline, it'd be in a 2x2 grid layout
tbh this is the only line with the word intent
bot = commands.Bot(command_prefix='&', intents=discord.Intents.all())
then its got the perms
perms = {
ctx.guild.default_role: discord.PermissionOverwrite(view_channel=False),
ctx.guild.me: discord.PermissionOverwrite(view_channel=True, send_messages=True, read_message_history=True),
ctx.author: discord.PermissionOverwrite(view_channel=True, send_messages=True, read_message_history=True)
}
game_channel = await category.create_text_channel(f"{str(ctx.author)}'s game", overwrites=perms)
await game_channel.send(content=f'{ctx.author.mention} your game will be played in this channel.')
where in the code would i have to add your intent msg
Um..dyno is the most customizable bot,,can do anything..ok then..but people says python is not good for discord bots..what does it mean?anyone know?
stop assuming things and making your own theories! this is how i got that output
-v jsk py ```py
embed = disnake.Embed()
embed.add_field(name="inline1", value="value")
embed.add_field(name="inline2", value="value")
embed.add_field(name="not inline1", value="value", inline=False)
embed.add_field(name="not inline2", value="value", inline=False)
await _ctx.send(embed=embed)
I don't know who says Python isn't good for discord bots
who tf told you that; It's really good for bots
easier said then done
gonna have to do some fun stuff to some lists to make that happen
mee6, carl bot, notsobot, poketwo are all made with python
Only python?
What language also probot/dyno used?
Often it's said that discord.js is closer to the API, e.g lower-level. discord.py is a bit more higher-level, sort of like a framework rather than a library, if you will. More features, heavier, that sort of things.
mee6 was with js iirc
We don't know, it's not open source
I don't think it's only Python
If they have a website, then likely HTML/CSS/JS is added into the mix
Oo
Carlbot is definetely discord.py. I talked to the creator a while back on discord.py, cool guy, learned some good stuff from him
nope.
sorry in advance but this message is a dogs dinner in the form of a discord message jesus christ
Carlbot is being rewritten in pycord afaik
even dyno doesnt uses the current state of discord.js
it uses eris which is a djs 8 fork
Wdym
huhh didnt know
They mean it's a pretty wild statement
just so much grammatical error is barely english
check their repo... its all full with python
Oh
If you count your own custom bots, I would argue that's more customizable than any other bot out there, since obviously, you were the one who created it
link? plz
no i do not
the bot is not open source ofc, but other dependencies are
https://github.com/Mee6/
weird
not bad code seems like they like having backwards compatibility because of format and forcing to subclass object
how can i make a command botowner only
!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").
"back words" hahaaaaa
😭
🤣
backward
i wish this channel was focused more on discord bot discussions than random topics.
@scarlet sorrel = literally flake8 for english
sorry auto correct
flakeate?
flakeght?
ESLint?
wat
english linter
😐 whatever
^
ok now explain flakeate
now in the @logoff.error
how can i respond to if they are not the owner
flake8 is a python linter
!pip flake8 one of the linters
see kids, jokes can go terribly wrong when someone doesn't understand
We use flake8 as a pre commit hook for most of our projects here at PyDis, very useful stuff so we can focus on actual code rather than stylistic errors
got black too?
no jokes allowed in 2022 im afraid
is it normal to have a bot which was just created to be ratelimited? :kek:
jokes are deprecated in 2022
a spamming bot?
XD. Ight I'm goin to bed yall have fun.
may your code be error free
it never started
ye
you using replit im guessing?
im running it locally as you can see in my activity, and again, it never started
Nah, just flake8, isort, some other stuff I can't think off the top of my head
I mainly work on non-python OSS at pydis (ironic, I know) so we usually use other tools
whats pydis
our org
whos org
python discord, this server...
our organization
anyaa :creepy:
:heh:
I refer to it that way because most of our open source projects are under the organization (literally, it's under pydis org in github), and I'm part of it
yall legit are not speaking english
its a name, which could be in any language.
who is anyaa
man i cant keep up
my english is so advanced that nobody even tries to understand it
its just the name of the project am working on + an anime character.
@sick birch you're probably older then me, how do you understand these people lmao
lol
You get used to it after a long time
💀
Especially with channels like these which tends to attract a lot more beginners, you tend to figure out how to fill in the blanks because when people ask questions here, it doesn't always follow the etiquette (if you can even call it that) for asking good questions
I don't blame them either, asking good questions can be difficult

