#discord-bots
1 messages Β· Page 1053 of 1
We don't help with music bots unfortunately, as it's in violation of TOS
check out tasks in the documentation, there are basic examples
well, please don't through YT
noone can teach me discord exactly π
π₯² ok
you need to set some goals first
instantly starting with a music bot is a steep learning curve
learn how to make a decent command with arguments etc first
i am focusing on 1 type of project cus im better in learning by doing
on the other hand i started a base base python class, but its only a programmer at the company that try to give us some knowledge :S
Like that
what changed?
!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.
Instead of loop
well, you still didn't START the TASK
it should not be a music bot, it should be only an extra function in a bacis bot and i failed at some point and try to figure out but oki, i will try somewhere else
thanks anyway π
How do I do it?
have you checked out the documentation with a basic example of a task?
YES I HAVE
send me the link as proof
Btw Iβm not using cogs
alright, as you can see, there's clearly a .start() method
doesn't matter, there are examples that don't use cogs
Oh
I see a .start
Do I do my_loop.start()
there are just people here that don't want to learn (they just want a solution to copy paste)
I'm not referring to anyone currently
I don't spoonfeed
try and see
you have to wait_until_ready
the second to last codeblock of the example shows you
basically, the bot's cache isn't loaded yet and you're trying to get a channel from it => this obviously results in it being None, which is why you can't send anything to it
some other notes about your code:
in the on_message, you should FIRST check if the author isn't the bot, THEN get the channel
logic behind this: why get the channel first if it turns out the author was the bot?
also this https://discordpy.readthedocs.io/en/stable/faq.html#why-does-on-message-make-my-commands-stop-working
If u know how to make discord bots with apis dm me right now.
Dude why am I keep getting this
MessageContentPrefixWarning: Message Content intent is not enabled and a prefix is configured. This may cause limited functionality for prefix commands. If you want prefix commands, pass an intents object with message_content set to True. If you don't need any prefix functionality, consider using InteractionBot instead. Alternatively, set prefix to disnake.ext.commands.when_mentioned to silence this warning.
client = commands.Bot(intents=intents)
Dude anybody?
dude?
.
!d disnake.Intents.message_content
Whether messages will have access to message content.
This applies to the following fields on Message instances...
Also enable it from ddevs portal
How can i fix this?
Seems like weatherjson is a list
so how could i fix it?
Can u print weatherjson?
1 sec
!d disnake.ext.commands.slash_command
@disnake.ext.commands.slash_command(*, name=None, description=None, dm_permission=None, default_member_permissions=None, options=None, guild_ids=None, connectors=None, auto_sync=None, extras=None, **kwargs)```
A decorator that builds a slash command.
no i cant
I said to print weatherjson...
my bad that works
Not able to see anything, paste the output here
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
thanks!
how do you make one of those buttons that does stuff when you click it?
!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.
I have another problem π Any ideas how to fix it?
tkinter decides to die when using discord.py, can anyone help?
thanks
Isn't tkinter blocking?
@sick birch can you give me a small example of how to add that button to a message?
well yeah and im trying to run both of them on a different thread and i honestly haven't dealt with threads in python
Ah threading
whats that
no button in that
tbh i have 0 idea of dealing with threads in python but i guess i'll search?
I need ideas for a name for a discord bot π
@sick birch how in the world do you get a button to create a text channel, because i cant see a way to pass guild to inside the interaction
interaction.guild iirc?
use interaction
arnt i?
import tkinter
from tkinter import messagebox
import threading
import customtkinter
from tkinter import *
import discord
from discord.ext import commands
customtkinter.set_appearance_mode("System")
customtkinter.set_default_color_theme("blue")
bot = commands.Bot(command_prefix='!')
root_tk = customtkinter.CTk()
root_tk.geometry("400x240")
async def open():
root_tk.mainloop()
@bot.event
async def on_ready():
messagebox.showinfo("Successfuly ran the bot!", f"{bot.user} Should be running now!")
def run():
token = "no"
bot.run(token)
button = customtkinter.CTkButton(master=root_tk, text="RunBot", command=run)
button.place(relx=0.5, rely=0.5, anchor=tkinter.CENTER)
bot.loop.create_task(open())
no not really
you can set a timeout tho, if no one interacts for 30 seconds lets say, edit the message, and disable the buttons
how do i get the names of the guilds the client is part of?
isnt it discord.ButtonStyle.green
i dont get it
ur making a website but u need discord button styles?
guys how do i use the pypresence library to give myself a custom presence?
it doesnt seem to be working for me
not really something related to discord bot, you can claim a help channel maybe
!pip pypresence
did you do all the stuff mention in the example/
can you get the bot to generate an invite to a sever its in?
i did
yes, that library sucks ass
#help-croissant @slate swan
!d discord.TextChannel.create_invite
await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates an instant invite from a text or voice channel.
You must have the [`create_instant_invite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_instant_invite "discord.Permissions.create_instant_invite") permission to
do this.
get any channel of that server , and create invite
how do i get just one channel of the server?
if you run the command from outside the server
!d discord.Guild.channels
property channels```
A list of channels that belongs to this guild.
but that gives them all
do you have just one server?
do you want to have a button inside ur bot to allow ppl to join ur bots server?
something like this
So I've got to the point in my bots code where I have a whole load of events so I was thinking about splitting the different type out into different files but keeping them grouped together in a events folder.
Should I:
A) make a folder within in my main dir (same level as my cogs folder) to store my events files
or
B) make a events subfolder in my cogs folder
How do I ask for input with discord.py slash commands?
Like this
I made that bot but I used another library, back when d.py was dead
probably a subfolder would be better
does discord.py have slash commands?
yes
the master branch, yes.
are you referring to discord-py-slash-commands, which is its own library, or discord.py
@flat solstice
from pathlib import Path
target_dir = Path.cwd() / "cogs"
for cog in target_dir.rglob("*.py"):
await self.load_extension(f"cogs.{cog.parent.name}.{cog.stem}")
This loads all .py files from all folders inside "cogs"
!d discord.app_commands.CommandTree dpy has slash commands in the next update
class discord.app_commands.CommandTree(client, *, fallback_to_global=True)```
Represents a container that holds application command information.
I used to use discord-py-slash-commands but with discord.py working again its better to use it
ive used dislash and then used the disnake fork
but am kinda bored with dpy , so i use hikari now.
idk my first contact with programming was discord.py so im used to it
please add py at the beginning of your message
ok one sec
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
async def on_message(message):
if message.author.client:
return
author = message.author
guild = message.guild
async with client.db.cursor() as cursor:
await cursor.execute("SELECT xp FROM levels WHERE user = ? AND guild = ?", (author.id, guild.id,))
xp = await cursor.fetchone()
await cursor.execute("SELECT xp FROM levels WHERE user = ? AND guild = ?", (author.id, guild.id,))
level = await cursor.fetchone()
if not xp or not level:
await cursor.execute("INSERT INTO levels (level, xp, user, guild) VALUES (?, ?, ?, ?)", (0, 0, author.id, guild.id,))
await client.commit()
try:
xp = xp[0]
level = level[0]
except TypeError:
xp = 0
level = 0
if level < 5:
xp = random.randint(1, 3)
await cursor.execute("UPDATE levels SET xp = ? WHERE user = ? AND guild = ?", (xp, author.id, guild.id,))
else:
rand = random.randint(1, (level//4))
if rand == 1:
xp = random.randint(1, 3)
await cursor.execute("UPDATE levels SET xp = ? WHERE user = ? AND guild = ?", (xp, author.id, guild.id,))
if xp >= 100:
level += 1
await cursor.execute("UPDATE levels SET level = ? WHERE user = ? AND guild = ?", (level, author.id, guild.id,))
await cursor.execute("UPDATE levels SET xp = ? WHERE user = ? AND guild = ?", (0, author.id, guild.id,))
await message.channel.send(f"{author.mention} has leveled up to level **{level}**!")
await client.commit()```
my error is something to do with this if message.author.client:
return
an attribute error
message.author
send the full error
Ok sure
Traceback (most recent call last):
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Dom\Desktop\cluckz\main.py", line 27, in on_message
if message.author.client:
AttributeError: 'Member' object has no attribute 'client'```
its for my leveling system
i think it's
if message.author.id == client.user.id: return
you don't want that the bot trigger itself
yes
what about message.author.bot
no
try this
so i dont want the bot to get levels basically if it makes sense
use this then
ok ima try it
client represents the bot
yes
so that should work
ima try
Traceback (most recent call last):
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Dom\Desktop\cluckz\main.py", line 38, in on_message
await cursor.execute("INSERT INTO levels (level, xp, user, guild) VALUES (?, ?, ?, ?)", (0, 0, author.id, guild.id,))
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\aiosqlite\cursor.py", line 37, in execute
await self._execute(self._cursor.execute, sql, parameters)
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\aiosqlite\cursor.py", line 31, in _execute
return await self._conn._execute(fn, *args, **kwargs)
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\aiosqlite\core.py", line 129, in _execute
return await future
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\aiosqlite\core.py", line 102, in run
result = function()
sqlite3.ProgrammingError: Cannot operate on a closed cursor.```
current error
not a dpy related error
error says it all though
i obvs know the error lol , idk how to fix it tho
ok
make sure the cursor isn't closed when doing an execution..?
yes
you are using your cursor after the "async with"
that's the problem
let me show you
cursor = connection.cursor()
conn.execute(...)
cursor.fetchone()
cursor.close()
# executing again will ofc result in this error
cursor.fetchone()```
Why does this not get rounded?
Can u help me fix that?
idk sqlite
read this or search for tutorial
Do u know sqlite or how to fix
we need to see your code ofc, we can't smell yours
are you getting an aerror?
No it just shows 27.45345345345 for example and doesnt round it to 27 e.g
you actually want timestamps, they are sexy asf, let me demonstrate
<t:1652995200:R>
I have quite a lot for the entire levelling system , what exactly should I show
you should know exactly at what line it errors and have a reproducable example ready of your error
I don't see any lines ofc
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.
that's not new
Weird
also read the last line of this
#discord-bots message
You are using the latest stable so Im pretty sure the only changes in code are for / commands, modals, menus etc
xD it still shows the error
Should I show my entire code on the web and paste link
correct
Ok
Sniper why bother editing it
your main issue is the
async with client.db.cursor() as cursor:
that's not what you want
what should i replace it with?
can you look very closely at line 18 for me?
as you can see, your if statement isn't in the context manager of the async with anymore
so anything starting from that line doesn't have an open cursor anymore
so how do i fix it?
exactly the same issue with line 54
you just make sure everything's in the async with
hell no
async with ...:
#shit
if ...:
# some stuff with cursor```
fix:
```py
async with ...:
#shit
if ...:
# some stuff with cursor```
so if moves forward
it needs to be INSIDE the context manager
ok
also, what db library are you using?
aiosqlite i think
thanks, this wasn't needed however as I already have a way to load my cogs.my question was more about file structure layout
I think
bruh, it's your code
also just seen this, thanks for the advice
Idk
Path.cwd() is very varying, you might wanna use Path(__file__) (the path of the current file ) and then move on from there
check the imports my guy
how do i disconnect a member from a VC? and to do that do I need pynacl discord[voice] support?
move_to(None) and yes
import discord
from discord.ext import commands
from discord_slash import SlashCommand
import aiosqlite
import random
import asyncio
import os
as you can read, it's aiosqlite indeed
Yes
okay thanks π do I need the pynacl voice support to use that?
I answered both your questions already
So whatβs the problem then lmao
have you ever checked out the aiosqlite docs?
ah, didn't see you sneak that yes in there
No why
then how are you even coding? you just GUESS?
Well nah I coded this like 2 weeks ago I checked the docs but I gave up ,
So Iβm trying to fix it rn
well, let me show you one difference
Ok
your code
await cursor.execute("SELECT * FROM shit)
vs an aiosqlite example https://aiosqlite.omnilib.dev/en/stable/
cursor = await db.execute("SELECT * FROM shit")
let's play the game, spot the differences
u add a cursor = and cursor.execute changes into a db.execute
yup, now change your code accordingly
Lol I forgot one thing in coding is that things will be updated
I added a link...
you should first learn how to use a db before implementing it in a command tbh
Hey,
Does anybody know how to create text like this in a discord bot?
How to display a list of missing bot rights, only without square brackets?
that's called an Embed
And how exactly do I call for a embed message?
you should check out the str.join(list) command
example
a_list = ["shit", "poop"]
joined_string = " ".join(a_list)
print(joined_string)```
This prints `shit poop`
none, it's a kwarg of the .send() method
.send(embed=embed)
β β.join(error.missing_permissions)
thanks you so much
Oh
Thank you too
@potent spear db is not defined
in your case, it's client.db ofc
So client.db.execute?
correct asf
If db is the cursor that is...if it is then it's pretty bad naming.
it's not, it's the connection
client.db = <connection>
at least, that's what I expect
something aint right
Thanks,
I'm kind of knew to Discord.py so would you be nice enough to maybe provide a example of a fully embedded text and print it?
async with client.db.cursor() is NOT what you need
bruh what then
that's something found in the docs or google if I'm honest π
alr thanks
I sent a link...
async with aiosqlite.connect(...) as db:
@potent spear it still doesnt work i need help xd
If you want the most basic example, I'll give you that
em = discord.Embed(title="yes", description="yes", url="https://google.com", timestamp=ctx.message.created_at)
em.add_field(name"bruh", value="k")
em.set_thumbnail(url="valid url")
em.set_image(url="valid url")
em.set_author(name="lol", icon_url="valid url")
em.set_footer(text="lol", icon_url="valid url")
await ctx.send(embed=em)```
most of these fields aren't even required
that's also incorrect
try to implement it outside of discord py first, you're moving too fast
#databases
just check out the example and start from there
No, I can't write the code for you
you first of all need to learn how to do basic CRUD operations (CREATE READ UPDATE DELETE) with aiosqlite outside of dpy
AFTERWARDS you can implement it in your bot
you spotted the differences already...
async with client.db.cursor() as cursor:
you should actually make helper functions, wouldn't that be nicer in your case?
lmfao all i need help with is fixing my code
so a helper functions which selects
(takes the following args)
select_from_db(db_connection, query, argument_tuple)
alright, if you want to keep it simple but not optimized, remove the async with
so just client.db() as cursor: ?
and then just after fetching with the cursor, close it via await cursor.close()
What's the package that makes it 'easier' to use buttons?
yes, that's even smoother
do that for every execute thing
async with db.execute('SELECT * FROM some_table') as cursor:
I need to see more code?
remove the shitty client.db.cursor() as cursor line and never use it in your life ever again
So I just remove it for every part and then my levelling system will work ?
the rest is just simple indentation
async with db.execute('SELECT * FROM some_table') as cursor:
result = await cursor.fetchone()
obviously becomes
async with db.execute('SELECT * FROM some_table') as cursor:
result = await cursor.fetchone()
Wait I have to add result = ?
when fetching something, that's quite obvious
result or xp or whatever your thing is
Ah so xp = and level = they just need indent
Which variable is responsible for deleting text in a text file?
Ye ?
what does this have to do with discord bots?
yup
man . . .
async def level_up(message, user):
with open("users.json", "r") as f:
loadJson = json.load(f)
start_lvl = loadJson[str(user)]['level']
end_lvl = int(loadJson[str(user)]['xp']*(1/10))
if start_lvl < end_lvl:
loadJson[str(user)]['level'] += 1
loadJson[str(user)]['xp'] = 0
loadJson[str(user)]['ssc'] += 1
await message.channel.send(f"Oh, {message.author.mention} has leveled up to level {loadJson[str(user)]['level']}!")
with open('users.json', "w") as f:
json.dump(loadJson, f, sort_keys=True,indent=4, ensure_ascii=False)
anyone have an idea why sometimes my members level up to the same level multiple times?
a json isn't a database
try and see
Why are talking about databases here? ;-;
I wont complain if someone guides me to the right discord thing to use buttons
there are examples in the docs yk
In the original one?
in discordpy?
yup
Oh
i remember people saying they used a different package for buttons.
didnt know discordpy used buttons
in the master version, they do
Also most of the newer features like slash commands, modals, context menus etc
I may need to update my discord py then π€
be aware, it has breaking changes and will require a rewrite
Thank you for the responses. Time to slap on my favorite music and figure this stuff out!
https://discordpy.readthedocs.io/en/master/migrating.html for reference.
Is self botting possible and is it against tos and can my account get banned if i do that
Yes, yes, yes
Does self botting mean controlling your main discord
Yes
Yes
I have to find sth that's a no π
Yes
No
Can i join that server with my main account and act like a bot
Yes
Yes
Thanks
Provide a bit more info "shit out" isn't really a valid description.
If i get banned does it mean i cant doscord anymore on that account
Yes
Can I delete and recreate account and do it again
Well. setting up and sending a button. Like it tells me all the stuff on the api but like, i cant figure out how to make a button xD
You'd violate the ToS then.
Really ?
Did you take a look at some of the examples in the dpy lib?
there are examples?
If you get banned on an account and remake one on a different name yeah, then you are avoiding the ban.
This is what I am using https://discordpy.readthedocs.io/en/master/
oooo
When a discord account is banned does it mean the name and discriminator cant be used anymore
No it just means the account is unavailable.
And if I delete the account can I make another one with the same name and id
You'd still violate ToS
Why does this sound like you want to do some super shady stuff right now? Like make a series of accounts that go around spamming discord servers and once the account is banned it just gets deleted and recreated?
Panda with the boolean answers
I'm planning to do anything, just curious
True
Don't get your account(s) banned.
I'm not stupid lol
"I'm planning to do anything" dunno kinda sus
I would make an alt but not this one, I'm already too popular in many servers π
I forgot not
I'm gonna give you the benifit of the doubt and assume you meant to say you aren't planning on doing anything
Isn't being popular a good thing tho?
lmao
How to get message.content not in on_message event
not really, no
Very good, they all know me for the bot I made
That's a good thing to be popular for
Rejected π’
it's personal dw

True. I wish people would use the bots I made π’
It's better if you think about it as a learning opportunity rather than trying to get a bot out for people to use
I only made one and it's already in 56 servers
Well for starters I didn't knew you have one.
How to get message.content not in on_message event
Where do you plan on using it?
Coz my bots for a very specific group of people xD
Get the message, need more Context tough. 
hilarious
π
I need to check if there is a youtube link in a user's post
that sounds like something you'd wanna do in on_message
I forgot the python inventer
I need to check this in the bot command
!d discord.ext.commands.Bot.wait_for
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message,
or to react to a message, or to edit a message in a self-contained
way...
speed
So a user runs a command, and you want to check if it has a youtube link in it?
Why would you ever need a yt url..?
yea
On the contrary, I need him not to be there
I have a question
Yes
def has_link(message: discord.Message) -> bool:
# Use regex or something else to check for a link here
return False
@bot.command()
async def command_name(ctx: commands.Context, ...):
has_link = has_link()
if has_link:
# do something
else:
# do something else
thanks you
is it possible to ask a question and get many answers at the same time without blocking
That might be the most useless var i've seen in awhile.
i find it readable Β―_(γ)_/Β―
!async
Concurrency in Python
Python provides the ability to run multiple tasks and coroutines simultaneously with the use of the asyncio library, which is included in the Python standard library.
This works by running these coroutines in an event loop, where the context of the running coroutine switches periodically to allow all other coroutines to run, thus giving the appearance of running at the same time. This is different to using threads or processes in that all code runs in the main process and thread, although it is possible to run coroutines in other threads.
To call an async function we can either await it, or run it in an event loop which we get from asyncio.
To create a coroutine that can be used with asyncio we need to define a function using the async keyword:
async def main():
await something_awaitable()
Which means we can call await something_awaitable() directly from within the function. If this were a non-async function, it would raise the exception SyntaxError: 'await' outside async function
To run the top level async function from outside the event loop we need to use asyncio.run(), like this:
import asyncio
async def main():
await something_awaitable()
asyncio.run(main())
Note that in the asyncio.run(), where we appear to be calling main(), this does not execute the code in main. Rather, it creates and returns a new coroutine object (i.e main() is not main()) which is then handled and run by the event loop via asyncio.run().
To learn more about asyncio and its use, see the asyncio documentation.
if you wanna remove it go ahead
For example I ask many riddles and whenever someone answers correctly their score is incremented
I'm coding in java rn for a weather app and I need to define so much.
wait_for is blocking
java or javascript?
It isn't but you most likely are in the same command.
it's called the language of boilerplate for a reason
java, it's android studio.
I want to make a riddle command for my bot
Java forces you into OOP design patterns way more than any other language
android studio's IDE is super sweet.
Not complaining.
i'm procrastinating learning kotlin and android stuff for a long time now π
!d discord.Client.wait_for
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message,
or to react to a message, or to edit a message in a self-contained
way...
Kotlin syntax kinda threw me off, I chose java since it looks a lot like c# (i wonder why).
Isn't Kotlin suggested for this sort of thing?
I know but I need the timeout to expire if no one answers without waiting
Pass in the timeout= kwarg
The problem is that I want multiple users to play
await bot.wait_for(..., timeout=60) # sets a timeout of 60 seconds
Not really java has been around much longer, kotlin is more going towards a mix of c# with rust.
I tried that, bot keeps waiting for a message
Just make the user who creates the game mention the user he want to challenge.

There was a trivia bot
Asks many riddles and if no one answers right after a minute it moves to the next riddle
wait_for catches all messages.
A while loop ?
Hmm I think I would solve this using a whole lot of OOP.
It's difficult you see
I would still use an on_message event.
Pandabweer: have you seen java's "Hello World Enterprise Edition"? google it, it's hilarious π it's a gag code
I got into java 2 days ago
How ? I already defined on_message to process commands
Just make it a listener
Cog ?
You should use cogs anyhow..
But how can I integrate the listener inside the command
how do i do something like
for guil in bot.Guilds:
for chan in guil.channels:
var = chan
invlink = await var.create_invite(xkcd=True, max_age=0, max_uses=0)
print(invlink)
but without the 2nd loop?
You don't you just make it globally available
We won't help you do this here.
This has been discussed before and is inappropriate enough to not be allowed here.
No you are creating invites for all servers.
ye
Does it fall within tos too
But it's not something a server owner wants you to do
It doesn't break ToS since people gave permission to create invites to the bot. But it has been discussed by the regulars of this channel and staff to be deemed inappropriate due to privacy.
True, private servers would not be private anymore
There just wasn't a good valid reason why you would need to do this.
public*
What if I make an invite link on a private server my bot is in
they dont put people in prison for not having enough of a good reason to do something
how to make a bot delete a certain line in a txt file?
you cant
if the server is private the bot cant make the link
Are you sure
It's pretty messy but what do you got so far?
yes
I didn't understand)
If the permission is given to the bot he can just create an invite.
According to Discord's Developer policy,
process Discord Data in a way that surprises or violates Discord usersβ expectations.
and mass-creating invites of every server your bot is in is definitely surprising, not to mention it's a very poor way to handle discord/user's data
server invites are not user data
Can someone help me asking for input with a slash command using discord.py
Why not?
and its not exactly a surprising thing to do considering that im asking
how would they be?
To your users, not us
if I have a server and a bot sends an invite link to everyone in another server I will be mad
wat
thats not what it does at all
If there was a valid reason for doing this okay, but so far you just avoided the "why" and just started to question our previous decisions.
because i want to see all the servers its in and be able to join them
obviously...
That's definitely against tos imo
And that is exactly what we're trying to avoid.
Heyy if any expert here can look ay #help-cheese
why
My bot is in 56 servers, and everyone knows me, they'll be surprised if just join their servers without their consent
need help w this code
@commands.has_role('MAGIC')
async def gendaily(ctx):
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
key = 'DAILY'
for x in range(20):
key += random.choice(chars)
await ctx.send(key)```
i want when user doesn't have a role that it says contact the owner
```do i do it like this orr
@bot.command()
@commands.has_role('MAGIC')
async def genweek_error(ctx, error):
if isinstance(error, commands.MissingRole):
await ctx.send("Error has occured please contact the owner!")```
your not in your own friends servers HAHAA
some friends
"process Discord Data in a way that surprises or violates Discord usersβ expectations." that literally is the ToS
No.
thats not against the tos
It's more of when a bot just displays information like what guilds it's in or the bot giving it's owner more privileges where I would never invite those kind of bots.
Can someone actually help me?
@gendaily.error
async def genweek_error(ctx, error):
if isinstance(error, commands.MissingRole):
await ctx.send("Error has occured please contact the owner!")
I dont think the command will run if you dont have the role, so your check wont trigger
!d discord.ext.commands.Command.error
@error```
A decorator that registers a coroutine as a local error handler.
A local error handler is an [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") event limited to
a single command. However, the [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") is still
invoked afterwards as the catch-all.
Changed in version 2.0: `coro` parameter is now positional-only.
post ur problem.
i got GPT3 to do it for me πππ
what the hell is happening?
whenever i run this code:
import discord
client = discord.Client()
@client.event
async def background():
await client.wait_until_ready()
channel = client.get_channel(CHANNEL ID))
await channel.send("Test")
client.loop.create_task(background())
client.run(TOKEN)```
I get this error:
```sh
/usr/bin/python3 "/Users/davidspieler/Library/Mobile Documents/com~apple~CloudDocs/Docum
ents/bot.py"
Task exception was never retrieved
future: <Task finished name='Task-1' coro=<background() done, defined at /Users/davidspieler/Library/Mobile Documents/com~apple~CloudDocs/Documents/bot.py:25> exception=Forbidden('403 Forbidden (error code: 50001): Missing Access')>
Traceback (most recent call last):
File "/Users/davidspieler/Library/Mobile Documents/com~apple~CloudDocs/Documents/bot.py", line 29, in background
await channel.send("Test")
File "/Users/davidspieler/Library/Python/3.8/lib/python/site-packages/discord/abc.py", line 1065, in send
data = await state.http.send_message(channel.id, content, tts=tts, embed=embed,
File "/Users/davidspieler/Library/Python/3.8/lib/python/site-packages/discord/http.py", line 248, in request
raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
please help. i have no idea whats happening
!d list
class list([iterable])```
Lists may be constructed in several ways:
β’ Using a pair of square brackets to denote the empty list: `[]`
β’ Using square brackets, separating items with commas: `[a]`, `[a, b, c]`
β’ Using a list comprehension: `[x for x in iterable]`
β’ Using the type constructor: `list()` or `list(iterable)`...
!h
why do you decorate the function and youre missing perms
i know I'm missing perms but i've double checked and triple checked and it doesn't look like i'm missing anything on discord's side.
How do I get the bot ID?
which one? the bot token?
Yeah.
Bot doesn't have access to channel id
which is fixed by...... doing...... what exactly? sorry I have little to no experiance with making discord bots
are you sure CHANNEL ID is a valid channel id
you didnt import id
no i just didn't want to display it to the server
yes
import channel id
what do you even want to do?
Also are here any experts with databases and discord.py?
i'm working on a bot that periodically sends a message to a specific channel in a server. im just working on the bot itself at the moment
so sends message on time?
yes but first i have to make it send a message at all
which as you can see is whhere the problem lies
you are doing it all wrong
oh thank god
i was worried it was something else causing the problem. You mean the code is wrong?
are there any sources you recommend? it seems the one i was using is- well not working out.
show me code
there are no sources
start with basics man
@slate swan
send it here
@commands.has_permissions(manage_channels=True)
async def addbutton(self, ctx, messageid:int, channel:discord.TextChannel, emoji: discord.Emoji, emojii: discord.Emoji, *, mg, *, msg):```
so what exactly you trying to do
!e
async def addbutton(self, ctx, messageid:int, channel:discord.TextChannel, emoji: discord.Emoji, emojii: discord.Emoji, *, mg, *, msg):```
@slate swan :x: Your eval job has completed with return code 1.
001 | File "<string>", line 2
002 | async def addbutton(self, ctx, messageid:int, channel:discord.TextChannel, emoji: discord.Emoji, emojii: discord.Emoji, *, mg, *, msg):
003 | IndentationError: unexpected indent
u didnt indent
I want that the mg and msg get all arguements that is puted using
Discord Glitch
How would that work
? What i do for it
With , we can separate?
@commands.has_role('MAGIC')
async def genweek(ctx):
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
key = 'WEEK'
for x in range(20):
key += random.choice(chars)
await ctx.send(key)```
i want when i generate key using this command sends the key to database unused collum
but when user does
.redeem it removes key from that collum
Hello
ctx.author.avatar_url```
would work right
and after they used key it has time when it expires
It's ctx.author.avatar.url in v2.0
If not on discord.py v2
But prior to that version, yes you are correct
ok
keys must have time when they expire tho
so lets say
it works thankx
i do .gendaily
makes key>>>>sends key into db collum
when user uses key the key expires in 1 day
Which is the best library for discord bots? Discord.py seems so bad compared to other options such as Pycord
how would i use if someone has a role or not
if ctx.author.role == "role id thing":
```?
wdym?
ok i want to have a command where it works if someone has a certain role
can someone help me with dbs and discord py?
mutedRole = discord.utils.get(ctx.guild.roles, name="Muted")```?
use @commands.has_role("Role")
ah thx i knew it was smth simple i just couldnt remember
try copying the guild id and putting it instead of the name
How can i manage my info using dbs
When i generate key using command that key goes to database
Can someone help me or nah?
@client.command()
async def redeem(ctx):
guild = ctx.guild
booster_role = discord.utils.get(guild.roles, name = 'Server Boosterγ»βΛβ§')
if ctx.author.role(booster_role):
await ctx.reply("yo!")
return
else:
await ctx.reply("You are not a booster my man")```
can anyone help its saying member object has no attribute role
what db
MySql
you have the table created ?
yes
what website do i write the code in
its roles,theres a list
i have the bot but what platform do i execute the code in
then you would store a row with the datetime .it was created
when it was used
and then if they try to use it, check that current time is no more than 24h after the creation time
how would i fix
key has been redeemed
what website do u guys use to write the code for the bot??
we dont use websiutes
does it have to be a website?
after key has been redemmed
anything im new idk where to execute the code from
so what do you want to do, kick the bot ?
@client.command()
async def redeem(ctx):
guild = ctx.guild
booster_role = discord.utils.get(guild.roles, name = 'Server Boosterγ»βΛβ§')
if ctx.author.role(booster_role):
await ctx.reply("yo!")
return
else:
await ctx.reply("You are not a booster my man")```
can anyone help its saying member object has no attribute role
no no no no
lemem explain it
when key has been redemmed
they get specific role
if booster_role in ctx.author.roles
and features of premium bot
what do u use??
vscode, pycharm, thonny, are all popular ones
so when the feature is used, check at that point ?
OMG no
you could use replit, visual studio code, sublime, etc
which one would u reccomend
none, try em all
they do.role and roles are added
replt is crappy but free hosting
im new and im just confused on how that code is implemented to the bot like we write the code in visual studio how does it execute in our bot?
and you dont know how to do that part ?
thanks, how would i make it so instead of the authors guild its a specific guild
i don't know anything
you do bot.run('token')
so lets make it clear,they get key,they redeem key and thier user id gets stored in db
idk
and if thier user id is in db they can do .role and get thier role
guild for what ?
maybe in the redeem command make the code sleep for 24h then remove role
thier user id gets removed from db
the guild the role is in
start the code from that?
that code makes the bot online
but u need more than that first
@livid hinge can you help me w that?
watch a yt tutorial
i know i sound annoying, do you have a specific youtube video i can watch i looked at 5 and all of them werent explaining like this
any just search how to make a discord bot in python
well i cant tell what you have already done vs what is still to be done vs what you are needing help with
OMFG LET ME MAKE IT CLEAR
no its ok
i haven't done anything just connected db
They get the key
do .redemm key
and when they redeemed key thier user id gets stored in db collum
await asyncio sleep?
after 24h thier user id gets removed from db clooum
@slate swan wouldnt this work
i don't know
in the cmd where they get the role
cause i have Daily,Weekly,Monthly,Lifetime key
give them the role and whatever then sleep for 24h or whatever then make it remove role
ok then do that
so they can't use the bot untill they renew premium feature\
@livid hinge is it clear rn?
@keen mural you got any idea how woudl i do it i'm stuck here for 3h lol
so when they redeem smth
u want to wait 24h then perform another action
no no no no no no no no
Let me make it clear
they redeem key and they have 24h to use premium features of the bot after those 24h thier premium version of bot expires untill they get new key
Sup guys
from discord.ext import commands
bot = commands.Bot(command_prefix="!")
@bot.event
async def on_ready():
print("we are alive")
@bot.command()
async def hi(ctx):
await ctx.send("bye")
bot.run("PTY1LDU1NjImMzkxNMDQw.GlrLme.I_qLkmbLmMN8xM3wtkeTySBDCTyc75vocJ89")```
Does my code look ok. Also not my real token lol
ok, when they redeem put them in the data base, sleep 24 hours, then remove them?
the concept of that
exactly
from discord.ext import commands
bot = commands.Bot(command_prefix="!")
@bot.event
async def on_ready():
print("we are alive")
@bot.command()
async def hi(ctx):
await ctx.send("bye")
bot.run("PTY1LDU1NjImMzkxNMDQw.GlrLme.I_qLkmbLmMN8xM3wtkeTySBDCTyc75vocJ89")```
but key must be one i generated
Getting this error
Guys is my code ok?
How do i fix it
"sleep 24 hr and then remove them" is exactly the same as "wait 24h then do another action" which you said was wrong fyi
you either do something after 24 hours to "expire" the features (e.g. removing roles) or you don't
well it has your token in it so you need to reset it
unless it's a fake one
it doesnt remove roles
it removes user from db thier user id
then what did you mean here
omg listen when THIER USER ID IS IN DATABASSE they do . role and role stays forever
but after 24h they get removed from db
it looks about right
so how woudl i make that work?
i know you are frustrated but thats no reason to shout at us
yes i'm sorry i've been stuck fot 4hrs now...
Anyone wanna help.
and i didn't move from db connection
like i have 0 ideas
did you try it @stoic scarab ? did it not work
Taking forever to load
how could i make a cooldown on a command to only certain ppl
i think you're missing something about intents probably
Huh
Can u check idk what Iβm doing tbh
@livid hinge Can you help me with my problem?
from discord.ext import commands
bot = commands.Bot(command_prefix="!")
@bot.event
async def on_ready():
print("we are alive")
@bot.command()
async def hi(ctx):
await ctx.send("bye")
bot.run("PTY1LDU1NjImMzkxNMDQw.GlrLme.I_qLkmbLmMN8xM3wtkeTySBDCTyc75vocJ89")```
it's a non-slash command , right?
Only if u help me with mines
Itβs !
What do you even need
See my code trying to make my first bot
Yeah and?
Failing so far lol
i dont think they give you message read access by default anymore ?
Whats output error
Wanna know why itβs taking forever to load
The program wonβt loaddddfd
No load as In get it running on ide
DO you have all modules installed
i'ma break something rn
Huh
Sheesh no need to be so mad lol
i've been faling db connect for 4hrs now second day
Well wanna help me succeed in my quest
Pls pls pls pls pls pls
i dont use repl
Itβs a ide not a whole new language lol
@livid hinge Wanan help me or nah ?
Help meeeee pls @slate swan
whats your problem
try smth new then
instead of yelling at people on discord
i need this
Why wonβt it loaddddf
from discord.ext import commands
bot = commands.Bot(command_prefix="!")
@bot.event
async def on_ready():
print("we are alive")
@bot.command()
async def hi(ctx):
await ctx.send("bye")
bot.run("PTY1LDU1NjImMzkxNMDQw.GlrLme.I_qLkmbLmMN8xM3wtkeTySBDCTyc75vocJ89")```
like you click it and instant closes?
No is stuck on resolving dependenceβs
hmm never seen that
Oof
you might need to do
from discord import Intents
intents = Intents.default()
intents.value |= Intents.message_content.flag
...
bot = commands.Bot(command_prefix="!", intents=intents)```
Pls explain everything
what output are you seeing tho
I just started discord.py lol
Just stuck on resolving dependenceβs
i've told you that i don't have problem with db connect and you told me that i have to look into my db and i clearly told you that idk how to code what i need
Like no out put or error
whats the actual output b/c i am not familiar with this description
im saying you need to learn how to use your database in general like get info from rows and stuff
search up examples of it and learning courses
screenshot ?
i alr know that. i just have 0 ideas how woudl i make it work
Itβs been running for 3min now
its repl it error
Bruhhhhhhhhhhhhhhghhhhhhnnj
thats pretty normal I'm afraid
Huh
Oof I saw with selenium lol
poetry slow on replit
nothing good
whats the best hosting
i edit the .replit file to disable poetry lol
for small bot
any vps up to 1gb
do vps's ever go down
speaking of which i just ran out of space on my vps today and have no idea why, i deleted tons of stuff and its still at 94% used
but idk what next to do
udev 364212 0 364212 0% /dev
tmpfs 75060 5428 69632 8% /run
/dev/vda1 11582072 10316104 659884 94% /
tmpfs 375288 0 375288 0% /dev/shm
tmpfs 5120 0 5120 0% /run/lock
tmpfs 375288 0 375288 0% /sys/fs/cgroup
tmpfs 75056 0 75056 0% /run/user/0```
idk how yo make that the key expires in 24h thats the problem
in the command that generates the key sleep for 24h then remove the key from the database
why woudl sleep for 24h?
that will hold key for 24h
yeah
each key must last 24h
i will hve multiple users using premium version of the bot
so i will need more than one key
@keen mural
ok
You leaked your bot's token
Re generate it on discord.com/developers
just in case
I still have 0 ideas how woudl i make that work can someone help me or not lmao?
MagicRay: set expiration date on each key
and run sweeping script that every hour removes expired keys
apparently it was a fake one
i guess that's why the bot didn't catch it
looks almost real tho
it's a bit complex problem ... persistency and expiration
do you need to know when the key has expired (harder to do) or just need to know if key is expired at the moment you use it (easier)?
gotta admit i am curious why they would go to all the trouble of faking one instead of just writing TOKEN lol
Hey greyblue
yo y9zu π
ππ
is there some kind of checksum in the token?
Thanks for help me :D, i forgot give you thanks, thank you so much
Thanks for help me too, i also forgot give you thanks
i need to know when key has to expire
after user redeemed
what are you trying to make?
a bot that has premium features
what you define premium as can have multiple other things
just commands that normal users don't have
but it must use key system
now = datetime.utc.now()
embed.set_footer(text=(datetime.now(timezone("Asia/Kolkata")).strftime('%H:%M:%S')), icon_url=self.bot.user.avatar.url)
await channel.send(embed=embed)
ord/client.py", line 375, in _run_event
await coro(*args, **kwargs)
File "/home/runner/mv/cogs/dev.py", line 65, in on_command
AttributeError: module 'datetime' has no attribute 'utc'
Why are you using keys, that just complicates things more. you could just add the premium users ID's to a database then check if the person running the command is in that database
but my keys have Daily,weekly,monthly and lifetime
I see
and i don't want to do it all manually it woudl take time
i can jsut restock keys
I'm not sure
would be cool to know that
can you help me w it or?
bad solution: add key, set timer to 24h, remove it, message the user it has expired
good solution: add key with expiration time, every time user issues the command check for expiration date
Well all i want to do is
bad solution explanation: you need to maintain processes/variables that count time, and renew them at bot restart
if user redeems key for 24h thier user id is 24hrs in db
rud0lf is definitely more capable than I am on this matter
after 24h thier user id gets removed aand they cant use bot untill they buy a subscription
i just get brief idea of the logic of code, i have not much experience with databases...
welp
i need somehow to make key last for 24h
maybe we can figure something out... may i pm you?
Sure go ahead
Nonetype object has no attribute
well this is in nextcord so can someone help me get the datetime object?
could you show the whole traceback?
you sure created_at isn't deprecated?
Well Iβm assuming thatβs a slash command so the message hasnβt actually been sent yet. Use nextcord.utils.utcnow()
It's inter.Message.created_at
I believe.
for py @commands.has_role("<@&926240974928228352>") how would i make it the id
just specify it
@commands.has_role(926240974928228352)
it takes a string or an int
if it's string, it checks name
if it's int, it checks id
@keen mural
how to i make a bots prescense dnd?
!d discord.Client.change_presence
await change_presence(*, activity=None, status=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Changes the clientβs presence.
Example...
Use the status kwarg and do status=discord.Status.dnd
should use the kwarg in the Bot class
!d discord.Status.dnd
The member is βDo Not Disturbβ.
Or that, yea
is there anyone in here who can help me transform my whole help, cog help and group help command to something specific that i have in mind?
would be very much appreciated
it's a subclassed help command, with the whole mapping stuff
How do I get channel id in py-cord? Why is discord.TextChannel not having id attribute?
code```python
def get_command_signature(self, command):
return '{0.clean_prefix}{1.qualified_name} {1.signature}'.format(self, command)
async def send_bot_help(self, mapping):
embed = discord.Embed(title="Help")
for cog, commands in mapping.items():
command_signatures = [self.get_command_signature(c) for c in commands]
if command_signatures:
cog_name = getattr(cog, "qualified_name", "No Category")
embed.add_field(name=cog_name, value="\n".join(command_signatures), inline=False)
error ```AttributeError: 'NoteBoyHelpCommand' object has no attribute 'clean_prefix'```
!d discord.TextChannel.id it has...
The channel ID.
I'm talking about py-cord not discord.py
It isn't in the docs, but all the objects have the id attr
Why yall using format like f-strings exist
They are more readable imho
clean_prefix doesn't exist (at least I couldn't find)
Where would you bring it from
@azure scroll
Is it some fork
mb
can someone help me?
it is a command method 
oh wait i read clean_params, my bad
!d discord.ext.commands.HelpCommand.clean_prefix
No documentation found for the requested symbol.
I knew I read that somewhere
its clean_prefix
Yea
π i don't really see its usage tho
its just f"@{Client.user.name}#{Client.user.discriminator}"
actually,just name
Acc to me, isn't it literally message.content.replace("<@id>", "@name")
indeed
π with regex prolly
im surprised why didn't this work tho.. removed in 2.0?
uhm tbh Command.name retrieves the name of the command without the prefix 
!d discord.ext.commands.Context.clean_prefix @slate swan
property clean_prefix```
The cleaned up invoke prefix. i.e. mentions are `@name` instead of `<@id>`.
New in version 2.0.
Weird that it isn't a method
ah its a context thingy now, its not in the Context object in the stable branch
Hm
how do I get the first, say, 100 members who joined the server?
import json
import tkinter
from tkinter import messagebox
import threading
import customtkinter
from tkinter import *
import discord
from discord.ext import commands
def getprefix():
prefix = entry2.get()
with open('config.json', 'r') as f:
prefixes = json.load(f)
prefixes[str("Prefix")] = prefix
with open('config.json', 'w') as f: # writes the new prefix into the .json
json.dump(prefixes, f, indent=4)
config = json.load(open('config.json'))
preshix = config.get('Prefix')
bot = commands.Bot(command_prefix=preshix)
root_tk = Tk()
root_tk.geometry("400x240")
async def open_window():
root_tk.mainloop()
@bot.event
async def on_ready():
print("ready")
@bot.command()
async def gay(ctx):
await ctx.send("You are the gay")
token = "ew"
entry2 = Entry(width=25)
entry2.pack()
button2 = Button(root_tk, text="Set prefix", command=getprefix)
button2.pack()
bot.loop.create_task(open_window())
bot.run(token)``` maybe there's a way i can run both of them ?
how do you m ake a discord bot with python