#discord-bots
1 messages · Page 921 of 1
Error handler
no shit
Scopes are basically "requests" but you will make. Adding more scopes widens your range of data you can access but it does come at at a cost since some people aren't comfortable of sharing certain information.
https://discord.com/developers/docs/topics/oauth2#authorization-code-grant here you can read more about scopes and oauth grant.
tyty that's what it's called
theres nothing in console either
Yes no shit
i removed the client.run(TOKEN) and the client.run(GUILD) and it's outputting the message in the console, but the bot's still not working
!d discord.ext.commands.Bot.on_command_error
await on_command_error(context, exception)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The default command error handler provided by the bot.
By default this prints to [`sys.stderr`](https://docs.python.org/3/library/sys.html#sys.stderr "(in Python v3.10)") however it could be overridden to have a different implementation.
This only fires if you do not specify any listeners for command error.
how do i make it send a message in the discord channel once it has connected
Run async function when initializing the bot. Don't use "on_ready" event.
not totally relevant to discord.py but a good package for mongoDB?
!d discord.ext.commands.Bot.wait_until_ready ^^
await wait_until_ready()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits until the client’s internal cache is all ready.
Warning
Calling this inside [`setup_hook()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.setup_hook "discord.ext.commands.Bot.setup_hook") can lead to a deadlock.
how can I get/fetch in a cog?
motor is async and recommended to use with mongodb.
!d discord.ext.commands.Bot.get_cog
get_cog(name, /)```
Gets the cog instance requested.
If the cog is not found, `None` is returned instead.
Changed in version 2.0: `name` parameter is now positional-only.
thanks
no, I meant getting roles/users/channel using get/fetch inside a cog file
Just client.get_user, client.get_role
Well by using the right object.
!d discord.ext.commands.Bot.fetch_channel
await fetch_channel(channel_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`abc.GuildChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.GuildChannel "discord.abc.GuildChannel"), [`abc.PrivateChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.PrivateChannel "discord.abc.PrivateChannel"), or [`Thread`](https://discordpy.readthedocs.io/en/master/api.html#discord.Thread "discord.Thread") with the specified ID.
Note
This method is an API call. For general usage, consider [`get_channel()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_channel "discord.ext.commands.Bot.get_channel") instead.
New in version 1.2.
Changed in version 2.0: `channel_id` parameter is now positional-only.
not working in a cog
it's self.bot inside a cog. You also need to make it a method to access self.
You can make it like this but i don't recommend it.
Well you are using OOP to define methods and attributes now with self.
So you can't have "self" outside the scope.
no
!e ```py
class Test:
def init(self, name: str) -> None:
self.name = name
@property
def g_name(self) -> str:
return self.name
t = Test("dave")
print(t.g_name)
@cloud dawn :white_check_mark: Your eval job has completed with return code 0.
dave
is this in a cog
yes
no
We can access name inside the method because we pass "self" but you are doing it outside of a scope.
because you can use ctx.guild.get_role
bot (commands.Bot) or client (discord.Client) has no fucn, named get_role. You get the role from the guild. So basically its guild.get_role().
Watch your indentation. its wrong
are you using this inside of a command or an event
Guild
It isn't.
@static beacon ^^
what context is "it isnt" in. is it just placed raw in the file?
Outside of the scope.
but why? you can just use this in a command where ctx is available and use ctx.guild.get_role..
lets ignore role for once, bot is stil not working when I use get_user()
its fetch_user and the get_user alias was removed in 2.0.0
show codes
I actually need them in multiple commands
Because it is defined as "self.bot" you can only access self inside a method.
you can just reuse it with some nifty ctrl + c & ctrl + v
get_user() still works,
oh okay, Self
really? it hasnt for me and ive done it on pre 2.0.0 and it worked.
just create a method inside the cog and use it 
yes. this.
class Cog(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
self.user = bot.get_user(USER_ID)
https://tutorial.vcokltfre.dev/tutorial/04-pong/ Have a look at this.
If the bot is really big this will most likely fail.
no, its just need to be "ready", and has member intents enabled
I figured out the correct buy, but this one doesn't work
the user may not be cached
Not really since "get" is cache and can return None.
@honest shoal this
But you can't have async inside an init anyways without some hacky tricks.
no I didn't test it, here
indenration
Like i said before you can't have self outside of the scope.
ohh my bad
self=.......
nevermind
yea...
class Roles(Cog):
def __init__(self, bot):
self.bot = bot
def return_roles(self) -> dict:
yellow = self.bot.get_role(id)
blue = ....
red = ........
return {
"yellow": yellow,
"blue": blue
........
}
```you could do this
oh wait nvm, dont
for subclassing bot when making overriding the Context (making custom context),
class MyBot(commands.Bot):
async def get_context(self, message, *, cls=class_name):
return await super().get_context(message, cls=cls)
bot = MyBot(command_prefix='prefix')
Now I can use my bot variable like how I do without subclassing bot right?
Like ```py
@bot.command()
async def e(ctx):
pass
or ```py
@bot.event
async def on_message(message)
I don't think I need this part
Then we are looking at an Enum
🗿
Which is a class not a method.
well, your wish, but I suggest making a method which takes an id and returns a Role object
ohh
so that you dont have to do self.bot.get.... again and again
Well you already subclassed it. You just define it already.
I do recommend the use of cogs and instead of event using listeners.
- get or fetch
yeah make a getch
yeah example, and how does the use of cogs come here?
that example was for a main bot.py file by the way ^
from discord import Role
from discord.ext.commands import Context
async def getch_role(self, ctx: Context, role_id: int) -> Role:
return ctx.guild.get_role(role_id) or await ctx.guild.fetch_role(role_id)
Well since you already subclassed it i like to include that inside the main folder since it is a pretty big task.
The use of cogs here is to separate the events and commands from the base of the bot. This is so it is easier for other people
and later on yourself to find code.
!source
no but that was an example to show how i would use bot
@ui.button(label="Cancel", style=ButtonStyle.red)
async def confirm(self, button: ui.Button, interaction: Interaction):
await interaction.response.edit_message(content="Cancelled.")
``` do I need to defer here?
If you are waiting for it yes since it will error if no interaction has been made at the end of the function or after 3 seconds.
without defer they have 3 seconds to respond
thanks
can i contact you in PM?
If it is something related to Discord or coding no, if you have a personal question for me or about something else sure.
then nvm xD
I'd like to keep all coding and discord related discussions here :)
when I subclass context i lose all the defaultsend methods and stuff right?
no
No you copy them and you can override them.
you are merely making a copy of the class
no it would inherits them
do you guys prefer Ticketbot or TicketBot?
is there smtn like
if messages.embeds:
if messages.embeds.author == Slash_.mahn#0444:
await message.delete()
```?
2/UpperWord
no
.embeds in the Message class returns a list
can u enlighten me
makes sense
!d discord.Message.embeds
A list of embeds the message has.
no, but you can do ```py
if str(messages.author) == "Slash_.mahn#0444":
...
yes
aighty shall try tht
okay thank you
thenks
yeah but you should make content a needed argument and its Any
!d typing.Any
typing.Any```
Special type indicating an unconstrained type.
• Every type is compatible with [`Any`](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any").
• [`Any`](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") is compatible with every type.
yes that
iirc you cant send an empty message so set a valid value or make it required
content would just be a string though?
the value is NoneType would it send the instance as a string?
idk
when subclassing context do I use
class MyContext(commands.Context):
@property
def something(self):
return soemthing
you typehint with a colon rn youre assigning it
why would you?
: @slate swan
yes a colon
my bad updated the message
still not sure why you would return
i just checked a tag nevermind then
Sup im having trouble to find how im getting a ban Reson can someone help me Im using on_member_ban event
whats the problem exactly
no real way, you need to fetch the audit log
Oh ok
@commands.Cog.listener()
async def on_member_ban(self, guild, user):
async for entry in guild.audit_logs(action=discord.AuditLogAction.ban,):
if entry.target.id == user.id:
reason = entry.reason if entry.reason else "No reason provided"
break
Oh tnx
if you want a command that shows the ban reason for a member rather just put the ban reason in a database
or are you doing a logging type of thing
is Context usually subclassed in the main bot file?
Im just making logging in a channel
yes
But if it get's too big you can make a separate file. Usually people subclass the ctx for small things.
then i need to import in the cog files or is there any other way?
updated
!d discord.ext.commands.Bot.get_context
await get_context(message, *, cls=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Returns the invocation context from the message.
This is a more low-level counter-part for [`process_commands()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.process_commands "discord.ext.commands.Bot.process_commands") to allow users more fine grained control over the processing.
The returned context is not guaranteed to be a valid invocation context, [`Context.valid`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Context.valid "discord.ext.commands.Context.valid") must be checked to make sure it is. If the context is not valid then it is not a valid candidate to be invoked under [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").
This gets called on each command so you can just use ctx without import
!d discord.Message.edit
await edit(content=..., embed=..., embeds=..., attachments=..., suppress=..., delete_after=None, allowed_mentions=..., view=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the message.
The content must be able to be transformed into a string via `str(content)`.
Changed in version 1.3: The `suppress` keyword-only parameter was added.
Changed in version 2.0: Edits are no longer in-place, the newly edited message is returned instead.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") instead of `InvalidArgument`.
nevermind
this is correct right?```py
class MyContext(commands.Context):
async def neutral_embed(self, message, **kwargs):
return await ctx.send(embed=disnake.Embed(description=message, colour=disnake.Color.blurple(), **kwargs))
it's self.send and yes
oh yeah
is this correct?
class Bot(commands.Bot):
def __init__(self):
super().__init__(
command_prefix=commands.when_mentioned_or('='),
intents=Intents.all(),
case_insensitive=True,
owner_ids=[751814647346102303],
help_command=None,
test_guilds=[897292885056176240],
sync_permissions=True,
activity=disnake.Activity(type=disnake.ActivityType.playing, name="DM To Contact Staff")
)
async def get_context(self, message, *, cls=CustomContext):
return await super().get_context(message, cls=cls)
self.db = bot.loop.run_until_complete(aiosqlite.connect("discord_bot_db.db"))
self.launch_time = datetime.datetime.utcnow()
self.last_result = None
Is this for slash commands?
Nope
It has prefix commands and interaction commands like buttons, select menus and application commands (context menus)
lgtm
What's that mean?
Oh it isn't
i need to replace bot with self
okay updated, I forgot about that
also, what happens exactly when you run the code of your nickname? @boreal ravine
how does it print elipsis
it's basically just ```py
def _(function):
function(...) # ... is Elllipsis
_(print)
but in a one liner
so once I subclass this, I access for example my db by self.db even in cogs right?
uh you'd still need to do self.bot.dbin cogs
is it self.bot.db or bot.self.db?
self.bot.db
oh i meant in a main file
then bot.db
oh cool so i don't have to change anything
yes
!pypi aiofiles
did you install it?
Only at github?
Hey guys I had thise code which was running flawlessly and suddenly its showing this error
disnake.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
P.S. I tried it bfr one hour and it worked I tried it now and didnt change a word and it stopped
@cloud dawn what do I got to do?
add_roles
It was working bfr one hour or so and it suddenly stopped
the bot needs higher permission tlo give the role to that user
You coding on a website?
What is this error lol?
Ignoring exception in on_command_completion
Traceback (most recent call last):
File "/home/container/.local/lib/python3.8/site-packages/discord/client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "main.py", line 941, in on_command_completion
await channel.send(embed=ce)
File "/home/container/.local/lib/python3.8/site-packages/discord/abc.py", line 1422, in send
data = await state.http.send_message(
File "/home/container/.local/lib/python3.8/site-packages/discord/http.py", line 329, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
you can't send embeds
First of all dont think am a pyscho bcs I gave all that permission its just bcs its my test bot and is used on my server for test purpose
Second I already gave manage role permissions to the bot!
just read the error properly, you're missing perms
need to change the perms of the bot right?
ok thx :)
yes lol
u dont have perms to do that
but the bot can
there are 3 things the bot needs to add role
The bot has now owner perms but still can't send the message?
the author needs perms to change role, the bot needs high role
do you have a requirements.txt?
You sure you gave it for the bot role not just on dev portal?
Um are you sure you are authenticating with the right token? Because I dunno what else can be wrong with that
Yea I did
@bot.command()
async def пред(ctx, member: discord.Member = None, *, reason = None):
print(45)
if ctx.author.bot:
return
cursor.execute("""CREATE TABLE IF NOT EXISTS warning(guild BIGINT, userid BIGINT, warn INT, count INT, reasons VARCHAR);""")
base.commit()
print(1)
if member is None:
await ctx.send("Выберите участника")
if reason is None:
cursor.execute('INSERT INTO warning(guild, userid, warn, count, reasons) VALUES(%s, %s, %s, %s, %s)', (ctx.guild.id,ctx.author.id,1,1,'Отсутствует'))
base.commit()
print(2222)
cursor.execute('UPDATE warning SET warn = warn + 1 WHERE userid = %s AND guild = %s', (member.id, ctx.guild.id))
base.commit()
await ctx.send(f"**{member}** Выдал предупреждение {ctx.author.name} , причина ``Отсутствует``.")
else:
cursor.execute('INSERT INTO warning(guild, userid, warn, count, reasons) VALUES(%s, %s, %s, %s, %s)', (ctx.guild.id,ctx.author.id,1,1,reason))
base.commit()
cursor.execute('UPDATE warning SET warn = warn + 1 WHERE userid = %s AND guild = %s', (member.id, ctx.guild.id))
base.commit()
await ctx.send(f"**{member}** Выдал предупреждение {ctx.author.name} , причина {reason}.")
Nothing output except 45 and 1, why?
so like what should I do...
Idk what the hell is happening I even gave the bot admin permission still its not working
Any ideas man its not working at all
Hey Guys. I was wondering what is a good VPS for my discord bot, I live in the USA
I use Vultr
Best vps for hosting discord bots?
That's what he asked
?
.
.
Alright thanks man
Which plan are you using
The 10$ one
aiofiles == "0.8.0"
!d discord.ext.commands.Context.send
#bot-commands
sorry
@bot.command()
async def пред(ctx, member: discord.Member = None, *, reason = None):
print(45)
if ctx.author.bot:
return
cursor.execute("""CREATE TABLE IF NOT EXISTS warning(guild BIGINT, userid BIGINT, warn INT, count INT, reasons VARCHAR);""")
base.commit()
print(1)
if member is None:
await ctx.send("Выберите участника")
if reason is None:
cursor.execute('INSERT INTO warning(guild, userid, warn, count, reasons) VALUES(%s, %s, %s, %s, %s)', (ctx.guild.id,ctx.author.id,1,1,'Отсутствует'))
base.commit()
print(2222)
cursor.execute('UPDATE warning SET warn = warn + 1 WHERE userid = %s AND guild = %s', (member.id, ctx.guild.id))
base.commit()
await ctx.send(f"**{member}** Выдал предупреждение {ctx.author.name} , причина ``Отсутствует``.")
else:
cursor.execute('INSERT INTO warning(guild, userid, warn, count, reasons) VALUES(%s, %s, %s, %s, %s)', (ctx.guild.id,ctx.author.id,1,1,reason))
base.commit()
cursor.execute('UPDATE warning SET warn = warn + 1 WHERE userid = %s AND guild = %s', (member.id, ctx.guild.id))
base.commit()
await ctx.send(f"**{member}** Выдал предупреждение {ctx.author.name} , причина {reason}.")
Nothing output except 45 and 1, why?
what's ctx.author.bot?
?
below print(45)
Does not respond to bots
You don't need it, it's recommended in on_message listeners
hi all
ctx.author.bot -> ctx.author.bot.user
iirc commands don't invoke to bots by default
Will it work?
Traceback (most recent call last):
File "C:\Users\Niclas\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\player.py", line 118, in __del__
self.cleanup()
File "C:\Users\Niclas\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\player.py", line 241, in cleanup
self._kill_process()
File "C:\Users\Niclas\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\player.py", line 193, in _kill_process
proc = self._process
AttributeError: 'FFmpegPCMAudio' object has no attribute '_process'``` what do i do
No
bot checks if the member object is a bot
So what I have to put?
Use len(ctx.guild.members)
Ok
ctx.author.bot.user don't even exist
!d disnake.Guild.member_count
property member_count```
Returns the true member count regardless of it being loaded fully or not.
Warning
Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires [`Intents.members`](https://docs.disnake.dev/en/latest/api.html#disnake.Intents.members "disnake.Intents.members") to be specified.
Thought you have to user .user attr after bot
@scarlet hull ^
ctx.author.client.user
bot is a boolean?
asdjasd
use {} instead of ()
Ok
?
perhaps show your code
then we will decide if it breaks ToS or not

@client.command(name='play', help='This command plays music')
async def play(ctx):
global queue
if not ctx.message.author.voice:
await ctx.send("You are not connected to a voice channel")
return
else:
channel = ctx.message.author.voice.channel
try: await channel.connect()
except: pass
server = ctx.message.guild
voice_channel = server.voice_client
try:
async with ctx.typing():
player = await YTDLSource.from_url(queue[0], loop=client.loop)
voice_channel.play(player, after=lambda e: print('Player error: %s' % e) if e else None)
if loop:
queue.append(queue[0])
del(queue[0])
await ctx.send('**Now playing:** {}'.format(player.title))
except:
await ctx.send('Nothing in your queue! Use `?queue` to add a song!')
it does
message.author.client.user is a thing,
it does what ?
break ToS
Ok
why
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
docs don't even show discord.Member.client
Ayo
can i get banned for that now lol
preferably not
frightening python
await ctx.send(f"{ctx.guild.members}")
it's () not {}
Bruh
it's gonna look weird tho
any other ways to make music bots without breaking tos ?
that didn't work I've tried this for long time ago
then use this my bad sorry
you can't download music from youtube without breaking youtube's ToS
im not talking of youtube lol
what about spotify ? is that allowed ? lol
Probably not
I'd Use copyright free music
i was boutta say
but how do you check that in a bot
i basically just want my bot to chill 24/7 in vc and loop lofi music lol
non-copyright is ok
i could technically download mp3 files that are not copyrighted ig
yes
but it'd make sense if you had to download it manually and then use it
so you don't fuck youtube 24/7 with downloads
I don't know
author returns -> [Member, abc.User] and abc.User has bot/client attr and which returns boolean
voice_channel.play() what do i do in here if i want to play mp3 files
!d discord.abc.User
class discord.abc.User```
An ABC that details the common operations on a Discord user.
The following implement this ABC:
• [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User")
• [`ClientUser`](https://discordpy.readthedocs.io/en/master/api.html#discord.ClientUser "discord.ClientUser")
• [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member")...
!d discord.Member.bot
property bot```
Equivalent to [`User.bot`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.bot "discord.User.bot")
@bot.command()
async def пред(ctx, member: discord.Member = None, *, reason = None):
print(45)
if ctx.author.bot.user:
return
cursor.execute("""CREATE TABLE IF NOT EXISTS warning(guild BIGINT, userid BIGINT, warn INT, count INT, reasons VARCHAR);""")
base.commit()
print(1)
if member is None:
await ctx.send("Выберите участника")
if reason is None:
cursor.execute('INSERT INTO warning(guild, userid, warn, count, reasons) VALUES(%s, %s, %s, %s, %s)', (ctx.guild.id,ctx.author.id,1,1,'Отсутствует'))
base.commit()
print(2222)
cursor.execute('UPDATE warning SET warn = warn + 1 WHERE userid = %s AND guild = %s', (member.id, ctx.guild.id))
base.commit()
await ctx.send(f"**{member}** Выдал предупреждение {ctx.author.name} , причина ``Отсутствует``.")
else:
cursor.execute('INSERT INTO warning(guild, userid, warn, count, reasons) VALUES(%s, %s, %s, %s, %s)', (ctx.guild.id,ctx.author.id,1,1,reason))
base.commit()
cursor.execute('UPDATE warning SET warn = warn + 1 WHERE userid = %s AND guild = %s', (member.id, ctx.guild.id))
base.commit()
await ctx.send(f"**{member}** Выдал предупреждение {ctx.author.name} , причина {reason}.")
Nothing output except 45 and 1, why?
help me
seems legit
don't even know what that is
Help me pls
!d discord.User.bot
Specifies if the user is a bot account.
I think your if reason is None indentation is off
🤔
do you have an error
I think he used a command where he mentioned a Member
me dumb
No
well, is member and reason None?
yes, I also tried with the reason
Ayo, does anyone know a lot about coding discord economy bots?
what do you think those if statements do
?
swastik
How did you use that command? .пред(@slate swan, reason)?
.пред @tidal hawk or .пред @tidal hawk reason
Unindent if reason is None
the if statement is only true if member is none
Currently it only runs if you do not mention a user
._.
without the ping
You got it @slate swan?
Not really
@bot.command()
async def пред(ctx, member: discord.Member = None, *, reason = None):
print(45)
cursor.execute("""CREATE TABLE IF NOT EXISTS warning(guild BIGINT, userid BIGINT, warn INT, count INT, reasons VARCHAR);""")
base.commit()
print(1)
if member is None:
await ctx.send("Выберите участника")
return
if reason is None:
cursor.execute('INSERT INTO warning(guild, userid, warn, count, reasons) VALUES(%s, %s, %s, %s, %s)', (ctx.guild.id,ctx.author.id,1,1,'Отсутствует'))
base.commit()
print(2222)
cursor.execute('UPDATE warning SET warn = warn + 1 WHERE userid = %s AND guild = %s', (member.id, ctx.guild.id))
base.commit()
await ctx.send(f"**{member}** Выдал предупреждение {ctx.author.name} , причина ``Отсутствует``.")
else:
cursor.execute('INSERT INTO warning(guild, userid, warn, count, reasons) VALUES(%s, %s, %s, %s, %s)', (ctx.guild.id,ctx.author.id,1,1,reason))
base.commit()
cursor.execute('UPDATE warning SET warn = warn + 1 WHERE userid = %s AND guild = %s', (member.id, ctx.guild.id))
base.commit()
await ctx.send(f"**{member}** Выдал предупреждение {ctx.author.name} , причина {reason}.")
:(
wdum
youtube tutorial guy with horrible youtube tutorials
lol
could work
I mean someone that can help me
okay, i will check
like
just add it ```txt
discord.py
aiofiles
we can only help you if we know what you struggle with
DOes anyone know a lot about coding economy bots, and could help me
Don't forget the return !! @slate swan
just ask here
What's hard about it? If a user buys something then - the amount and when sells then +
almost everyone here can make an economy bot, but is used to helping those who know what they've got a problem with
like, yeah, its' verified, but the founder isn't really interested, the co-founder (me) doesn't know what to do, and the only dev is offline half the time let alone help me code the bot
And just do not store balance items etc in json
I'm gonna be going to College in a few years lik the founder, and won't have a lot of time
startin to love u
Can anyone help us with the codings?
Hahaha
jk
lol
!rule 9
bruh
are you familiar with python?
And please use appropriate language, even when you are joking.
sorry
but I'm a bit iffy on economy bots
hi guys
is every mod stalking like that? 
xD
but you know how to create a bot?
i stalk a server like for 4 hours my guy
imagine stalking o.o
Commited Discord mods
someone probably DMed @novel apex
nerdy
We have a bot that helps us.
im trying to make a join message that looks similar to this. I'm very new to python and im excited to learn!
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello! This is my only cmnd at the moment lol')
client.run('token')```
this is my code so far. I heard smth abt "member intents" but i do not know how to use those
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: source must be an AudioSource not str what do i do
source must be an AudioSource not str
no clue
musicdir = os.listdir("./music_downloads")
for file in musicdir:
voice_channel.play(file)
```e
in here lol
It's called an embed message
yeah but i dont know how to use on_member_join
@client.event
async def on_member_join(member):
your_channel = client.get_channel(id)
embed = discord.Embed(title=f"{member.name} joined {member}", description="blabla")
await your_channel.send(embed=embed)
help
you wanna download something and play it?
or yeah what ^ said
we have something in common, don't we
ey hows ur chess bot going
i wanna play the whole folder yes
wait
me?
ok
ok
dont i need member intents
I have no idea, probably lots in common
try this
you got two arms too?
got it from stack overflow but
from time import sleep
from pathlib import Path # for directory listing
import pygame
DIRECTORY = Path('./path/to/your/directory')
mixer.init()
for fp in DIRECTORY.glob('*.mp3'):
# add each file to the queue
mixer.music.load(str(fp))
mixer.music.play()
# now wait until the song is over
while mixer.music.get_busy():
sleep(1) # wait 1 second
this isn’t about discord bots…
I'm too lazy to code this, I can, but i don't want to
pathlib module
yes
what ?
!ytdl is a thing
is that message meant to me lol
.
its against tos
yes
against tos
bruh check this @desert badger
use path
Well that’s the point
like foxy said
ty
?
yw
if it doesn't work, I'll code it
making chess game, then I'll implement it
are you on mac linux or windows
nice
Go to #bot-commands and do !ytdl
chess.com
lichess.com
no
ok
thats nice
do i need that mixer thing ?
are u participating in pyweek?
no
hm
are u on mac, windows, or linux
if windows, prolly yes
windows
but idk about my discord bots host
@neat pagoda disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: source must be an AudioSource not WindowsPath
This error doesn’t make sense
When you have a embed in discord.py like that you have to include a description
Oh
So like
title="",description=""
Yeah that Ty lol
lol
hmhm
I don’t think you need a tile and a description
me too lol
That’s only for name and value
actually yea
idk why that error pops up
You can have a footer to but if you set it up the way he did you have to
i only need a title?
Let me look at how he set it up
i can use only title. thats weird
Not working same error
it was updated
I am confused
the description isnt required anymore
Oh that’s cool
The description should not be a problem, is it a indent error?
just spent 5 hours trying to fix a website error just to realize its in the css 
lmfao
i wouldnt prefer replit
r e p l i t
It looks good to me try resetting your repl
OH, you have some lines that MUST be indented in order for it to run properly
They are indented tho
Let me circle it
yes. its the repls problem
Yeah unless I’m blind they look indented
Never mind I’m an idiot lol
@formal basin refresh your screen if that doesn’t work delete the module files and reninstall
I think you can use netifly to host it for free. Or, I always rely on AWS.
Aws??? Lol for discord bots
It works
it works
It’s a pain in the ass to set up, but once you set it up it is easy to change. You have to do it a certain way for it not to be annoying.
Where can I host my bot for free 💀
Aight thanks 👌
your pc
Use uptime
or use https://up.repl.link/
Keep your Replit projects online 24/7, for free.
Don’t use repl!!
its pretty good
Nah it’s good
Honestly I don't like repl at all 💀
its not
Thank you lol
i just use my pc lmfao
I think it is
Okk thanks

use vsc and heroku
we need to curb stomp replit
I just used a raspberry pi when I started out lol
replit is for boomers
SAME. i had this old 4gb rpi that i was using for the longest time
Lol
Lol
Why
They are the best little contraption
For small projects it’s fine
it gets rate limited, it sucks, its laggy, it crashes all the time, resources are limited, just use your pc, turns off every 8 seconds.
it uses shared ips meaning if someone hosting a bot that gets rate limited ur bot will get ratelimited too
when all i have is a true or false variable in a database im too lazy to care
Yeah but still
I am hosting my bot there
Nd yeah it was unable few times
ratelimit go brr
lol
If you ever need help, google has everything 😂
its so much easier to just host on ur pc
So wht can i use intead of repl.it , i am a beggener at all this , trying to explore much i can
Netifly is free or use aws for pay
use visual code studio and heroku
ur pc
yes and ur pc
Can my pc be able to host it?
all you need
24 hrs
yes.
How
as long as you keep it on
you run. it work on your computer. it stay on as long as host stay on.
🙄 aint my laptop will fall sick , my poor laptop
use vps
Yes i k it i did it b4 , nvr thought u gonna tell me to keep it on 24 hrs
Nothing is working
not here edo
swas.py tut?
?
freecodecamp
EEK
he has keep_alive lol
ohh
Replit hosting
if theres underscores, its probably from a tutorial
No offense but that's cringe
i just use replit for the web development and then use cloudflare for everything else bc replit nameservers suck
true
Idk I have vsc for everything besides android dev
except you cant edit the 404 page
hmh
well you can, but its rlly finnicky
then ill have to remake the whole site in node
it seems to work for https://mechabot.tk/
Modernized, sleek, and user friendly, Mecha is everything you could ask for! With a stable and open TOS, privacy policy and more. Mecha is all about user experience, and creating a better tomorrow. For you, your members, and your server.
is that urs?
Anyone know what is wrong with the code
hmhm
were changing the color palette currently
fuk replit
hm
honestly just looking for criticism if you're open
Doubt anything is wrong with code most likely with request or data processing
Print the response code
90% you will have 401
It does nothing
it resets replits formatter
so it wont give shitty errors like that
and also catch them better
That’s a txt file
?
The image
were from disnake.ext import menus those menus deleted from disnake?
no
thats an extension, you gotta install it
extension?
yes
how do I install it?
it was for d.py, not sure if disnake has a monkey-patched version
!pypi disnake-ext-menus
download that :)
thx!
that looks 50% like a fork
obviously
That looks like a weird 10th party lib but that's only my opinion so don't pay attention 😅
one more question, where could I install jishaku?
with pip?
!pypi jishaku
A discord.py extension including useful tools for bot development and debugging.
thx, I messed up all my pip packages smh

Traceback (most recent call last):
File "C:\Users\Niclas\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\ext\commands\core.py", line 169, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\Niclas\Desktop\Other\Python\NcZ Discord Bots\NcZ\main.py", line 495, in play
vc.play(source)
File "C:\Users\Niclas\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\voice_client.py", line 605, in play
raise ClientException("Already playing audio.")
disnake.errors.ClientException: Already playing audio.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Niclas\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\ext\commands\bot_base.py", line 570, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Niclas\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\ext\commands\core.py", line 920, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Niclas\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\ext\commands\core.py", line 178, in wrapped
raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: ClientException: Already playing audio.``` how do i fix this error
just an asyncio.sleep(1) before the play thing ?
what are you playing? o.O
some copyright free mp3 file i downloaded
why
hello. What have I missed in 3 days?
Command raised an exception: NameError: name 'MyView' is not defined```
@commands.command()
@commands.has_permissions(administrator=True)
async def setup(self, ctx):
embed1 = discord.Embed()
embed1.set_image(url="")
embed = discord.Embed(title="", description="**")
embed.set_footer(text="", icon_url="")
embed.timestamp = ctx.message.created_at
em = [embed1,embed]
view = MyView()
await ctx.send(embeds=em, view=view)```
it says MyView is not defined but I have class MyView
!pip motor ic
yeah i need some examples because motor uses a different loop when is declared and from the latest version you can't give a loop when you declare the database
Can you show us where is the MyView located?
not even with asyncio?
imagine a class inside a class pffttt
today i tried to make it work, essentially i had to declare the database inside an async function and then call it with asyncio
in my bot i will not initialize the database using the bot loop, i want to create an utils folder where to put my essentials query, so i'm trying to find how others used it
?
Create the class outside the current class
try self.MyView or move the class outside the cog
please move it outside xD
idk if you can have that
well technically when you create an object inside a class you are using a class inside a class xD
HM
!e
class FirstClass:
def __init__(self): pass
class SecondClass: pass
c = FirstClass()
print(c)```
@slate swan :white_check_mark: Your eval job has completed with return code 0.
<__main__.FirstClass object at 0x7f1824f555a0>
didn't work
btw is not suggested to create class inside class i think, we are not in Java D_D
I have a little knowledge of basic python. where can i learn on how to make discord bots because the freecodecamp video on YouTube is outdated as the code doesn't work anymore
Send the whole code
Do you know how classes work?
can't, too much words in it
oh cool, nothing was understood by me
lol no but i will just copy code until i learn it
Bro I really recommend you to learn classes first, it doesn't take long and ur life would be much easier
OOPs and Asynchronous programming are a must since dpy is dependent on both of them heavily
Exactly
async with ctx.typing():
song_list = []
for f in os.listdir("./music_downloads"):
song_list.append(f)
chosen_song = random.choice(song_list)
pass
while True:
song_name = chosen_song.replace(".mp3", "")
em = disnake.Embed(
color = disnake.Color.purple()
)
if chosen_song.startswith("uppbeat"):
_song_name = song_name.replace("uppbeat", "")
em.description = f"**Now playing: {_song_name}**"
em.set_footer(text = "Downloaded from Uppbeat")
pass
source = disnake.FFmpegPCMAudio(f"./music_downloads/{chosen_song}")
vc = ctx.guild.voice_client
await asyncio.sleep(3)
vc.play(source)
await musicchannel.send(embed = em)
``` can anyone help me fixing this code? i keep on getting that `Command raised an exception: ClientException: Already playing audio.` error
what should i type
Bro you still here xD
nice
i had to do something like this:
async def insert():
client = motor.motor_asyncio.AsyncIOMotorClient("localhost", 27017)
#other stuff
asyncio.run(insert())
because this
client = motor.motor_asyncio.AsyncIOMotorClient("localhost", 27017)
async def insert():
#other stuff
asyncio.run(insert())
Threw insert() already in a loop error
what is that
i dont know
Send multiple images
yes yes i was googling what is asynchronous programming and oops
i tried taking a bot from github and it asked me for this
if ctx.voice_client: return await ctx.send("alreadt playing an uwu song)
# your music playing code must come here```
uwu song
ignore the typos
and the uwu
interesting
oh maybe i find something on github, hoping that will not be the stereotype of disocrd bot developer declaring client = discord.ext.commands.Bot()
@cold sonnet
no
Your bio worked!
kingbio
||fuck|| this ||shit|| i'm out
I feel them breathing on my poo-poo
😔
Everybody do be with creative names and bios
you guys are so funny ||oof||
I called sink something while kiddin and a mod came and got me good
never
Everyone's humor here is on another level so I will just go back to optimizing my game
mods love me and me Iove mods
You're their kitten?
yes
||no humour|| ||is not another level||
WHAT I'M SEEING
I can't rely on people who wrote like that 😩
😔 Or my IQ is too low to understand it
Wait brb gotta bleach my eyes
imagine copying my code
||Imagine if bot's cant read this||
well technically if a bot has a message event declared it actually can
is that really your code? D_D
Lemme show u my game's code
please no i can feel the pain without even openin' it
That's hot
..................
not really, danny made it originally
that's my coder
class Ticket_Bot(commands.Cog):
def __init__(self, client):
self.client = client
class MyView(View):
def __init__(self, client):
super().__init__(timeout=None)```
Or could you explain how its a class in a class or if theres a doc on it or smth
@placid skiff https://github.com/GitBolt/axiol/tree/master/axiol
idk if this makes any sense but might as well take a peek
I still gotta optimize it but meh
is it slow though
BTW are for loops faster than using slicing?
class MyView(View):
def __init__(self, client):
super().__init__(timeout=None)
class Ticket_Bot(commands.Cog):
def __init__(self, client):
self.client = client
not so sure, also i used slicing with lists and othere data types only for reverting them
Hmm okay
Whats the #type ignore mean? I see that a lot
it means that type checkers should ignore that line
meh seems more experienced that the code of that guy, so i'll give it a try
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
I think I will just go away from here
right
@slate swan stop ghost pinging people
bai
Old habit
huh?
Eh, if u talking bout my message reply, I did saw the ping so it doesn't count as a ghost ping
client isn't defined
😔 sad to see people try to act oversmart every time
Use interaction.guild instead of client
so to make a stupid example, to store some sort of Q:A i can do something like this:
Guild_Collection:
id_of_the_guild{}
some other stupid stuff{}
Question{
one_stupid_question{}
another_stupid_question{}
}
answer{
stupid_answer_for_first_question{}
another_stupid_asnwer{}
}
Right?
in python dict will be something like this:
my_guild = {"id": 1, "question": {"question_1": 1, "question_2": 2}, "answer": {"answer_1": 1, "answer_2": 2}}
Okay?
and so goes on, essentially can i store with mongo a dict which has a dict inside? lol
mm
well find my asnwer and is NO of course hahahaha
mh my mind isn't trained to work with json using mongo is the baddest idea i've ever had
my_guild = { "1": {"question_1": "answer_1", "question_2": "answer_2"}}
Will not work found this on stackoverflow
Why?
yes

channel1 = client.get_channel(879783539258847354) what of this? client is not defined
there is an async package for postgresql?
channel1 = interaction.guild.get_channel(879783539258847354)
Oh mongo
!pypi asyncpg
what do i need to make my bot allow to write to my github repository file?
oh, this is another command
@commands.command()
@commands.has_role("Middleman")
async def delete(self, ctx):
if ctx.channel.category.name!="Closed Tickets":
return await ctx.send("You can't use this command here!")
embed = discord.Embed(description="Deleting ticket in 5 seconds...", color=0xb92222)
await ctx.send(embed=embed)
await asyncio.sleep(5)
await ctx.channel.delete()
channel1 = client.get_channel(879783539258847354)
embed1 = discord.Embed(
title = f"{ctx.author.name}#{ctx.author.discriminator}",
description = f"**Logged Info:**\n Ticket: {ctx.channel.name}\n Action: Deleted",
color = 0xb92222
)
await channel1.send(embed=embed1)```
probably just a token
A git repo isn’t a file. You push the code and files you want to a GitHub repo
"github repository file"
what is that supposed to mean🗿
would bot.wait_for('message') return a message obj?
yes
nice

ok nevermind figured it out
Good job
If i have two instances of channel sus will inst1 == inst2 return True?
two instances of the same channel?
yes
I think so, but channel.id == channel.id is for sure
check message.content through words and send a message and delete it. its pretty easy with an on_message event
where said?
idk someone here just told me that
ignore what i said earlier no it would return False since theyre difference instances
but, it just worked

what worked
inst1 == inst2
!e
class A():
...
a = A()
b = A()
print(a == b, a is b)
@slate swan :white_check_mark: Your eval job has completed with return code 0.
False False


👀
bro its basic python lmfao
btw how you check who created a channel?
audit log?
hi okimii
print((password_generator:=lambda num:f"Your new password is:\n{''.join(__import__('random').sample('1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!@#$%^&*()_-+=|>.<,/?', num))}")(2))
what ive done

this looks horrifying
yes it is
hi hi
#esoteric-python get outta here

hey folks, I'm wondering what's a better way to send messages. output is very, very slow so I'm thinking I'm being rate limited
# my current one
lines = ['Hello..', ....]
for line in lines:
await ctx.send(line)
you can use embed
or you can use webhook to send a lot of msgs without rate limit (i think)
can I obtain chat history of my bot and a user?
cheers, so that's what it's called
yes, one sec
@client.command() / @bot.command()
async def history(ctx):
messages = await ctx.channel.history(limit=YourLimit).flatten() # you can change the messages var to the dm channel and it will work
for message in messages: # Get only the messages and not any extra information
print(message.content)
@honest shoal do you need any more help?
not ctx.channel
so?
I was asking about dms
i know
bot and a user
look at the comment
# you can change the messages var to the dm channel and it will work
do I need to create a dm
yes
I've had to redeploy my app 3 times, because i typed @commands.commands instead of commands, used a tuple instead of a list, and i did message.contentlower() instead of .lower()
so change messages var to await bot.fetch_user(id)
something like this
ho wait not ctx
bot
yes
I know how to fetch a user, but what will be defined as a channel there? or just the fetched var of user
dame
i think let me test it
!d discord.User check here
class discord.User```
Represents a Discord user.
x == y Checks if two users are equal.
x != y Checks if two users are not equal.
hash(x) Return the user’s hash.
str(x) Returns the user’s name with discriminator.
!d discord.User.dm_channel
property dm_channel```
Returns the channel associated with this user if it exists.
If this returns `None`, you can create a DM channel by calling the [`create_dm()`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.create_dm "discord.User.create_dm") coroutine function.
look:
disnake
nice rich presence
@client.command() / @bot.command()
async def history(ctx):
messages = await bot.fetch_user(id).dm_channel.history()
for message in messages: # Get only the messages and not any extra information
print(message.content)
just user.dm_channel which is similar to a TextChannel, so you can use the history method of it
yeah
you know whats better
?
@honest shoal look its working
i saw everything 🗿
😋 ToS delicious
yes
oh
c ya
about me haha
those buttons😭
what
bro lets talk
the language?
your home buttons
what are thoseeeee💀
tf is this
they look funnny
whare you get this from
what is that a motorola💀
stop
lmfao
cyberbully
im sorry its just the theme looks so 2000😭

u too
wat

what have i done?
selfbots


no i didnt
oh nice
im being nice and not reporting you
ok you cool
including myself
🥛🥛🥛🥛🥛
bro
bro

@marble rampart thanks, and is it possible getting the messages only of user not the bot?
but it sound more cool
but it sounds more cool
i think message class have info on the user and you can see there if the user it a bot or not
uh
can you n o t
this is my code rn py user = await _bot.fetch_user(727526184161902614) async for message in user.dm_channel.history(limit=3): await _ctx.send(message.content)
ok when sec
now wait
il check something
!d discord.TextChannel
class discord.TextChannel```
Represents a Discord guild text channel.
x == y Checks if two channels are equal.
x != y Checks if two channels are not equal.
hash(x) Returns the channel’s hash.
str(x) Returns the channel’s name.
🗿
discord.DMChannel.history() returns a list of messages class right ?
lemme check
I'm so done
what's the syntax for an async iterator method
in the bot
!d discord.abc.Messageable.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the destination’s message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.
Examples
Usage...
if it is so you can use author.user and get a lot of info about the user/bot that sent the message
just got it
then you check if its a bot or not
Specifies if the user is a bot account.
indeed
this confused me
basically you have a list of messages from history
which you use in the for loop
async for message in channel.history():
then you check if message.author.bot
which will either be True or False
thats right

