#discord-bots
1 messages ยท Page 1138 of 1
If you're having trouble understanding the documentation, id recommend reading up on OOP in python. It'll make sense after that
Corey Schafer has a good set of videos on OOP on YouTube if you're interested
okay will do tysm its been years since i learned java so i can't deny that i don't really remember oop 
@bot.command()
async def timeout(ctx, user: discord.Member=None, time=None, *, reason=None):
time = humanfriendly.parse_timespan(time)
await user.timeout(until = discord.utils.utcnow() + datetime.timedelta(seconds=time), reason=None)
await ctx.send(f"Timedout.")```
datetime.timedelta, not datetime.datetime.timedelta
thats what im using
show full traceback?
like the fulll error
No, you're importing datetime from datetime
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 181, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\user\Desktop\Discord Bot\Foxx\main.py", line 726, in timeout
await user.timeout(until = discord.utils.utcnow() + datetime.timedelta(seconds=time), reason=None)
AttributeError: type object 'datetime.datetime' has no attribute 'timedelta'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 360, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 927, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 190, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: type object 'datetime.datetime' has no attribute 'timedelta'```
Either ```py
import datetime
datetime.timedelta
orpy
from datetime import timedelta
timedelta
give ur bot permission
admin permission
it does
The bot's top role needs to be higher than the target user's top role
oooh
And I would recommend not giving your bot admin permissions, only give it what it needs
!e print('a')
@scenic grove :white_check_mark: Your eval job has completed with return code 0.
a
wow cool
nvm just tested the bot))
ooo
wdym by "do tons of commands" and what disadvantage?
i mean if i let it control music, built up games, do lots of command asked by the user
BASICALLY I MEAN IF THERE IS ANY LIMIT๐ญ
like could i add and add commands for the bot to do?
there is no limits to how many commands you can have
the only limit would be your processor, which i doubt you will ever cross
oh
ok nvm<3
i have an i7 10th generation so i actually don't think it will keep tbh
huh?
yo
yesterday with the help of @torn sail we made this code
bot.embeds = {}
@bot.command()
async def mdc(ctx):
embed = discord.Embed(colour=0x0000FF)
embed.add_field(name='Nรฉv', value='โ', inline=True)
embed.add_field(name='Indok', value='โ', inline=True)
embed.add_field(name='Dรกtum', value='โ', inline=True)
ctx.bot.embeds[ctx.author.id] = embed
await ctx.send(embed=embed)
@bot.command()
async def addmdc(ctx, namee, reason, date):
embed = ctx.bot.embeds[ctx.author.id]
fields = embed.fields
fields[0].value += namee # or whatever your variable is called
#now we can do the same thing for your other arguments
fields[1].value += reason
fields[2].value += date```
u would have to make couple million commands to make ur processor not keep up
o
The mdc message sends this which is good.
YAYA
and if I run addmdc yo yo yo , then run mdc agaian
yo yo yo will appear
but this isn't working
could someone help me with #help-lollipop please?
uh any1?
imagine accessing bot through a property when you have the direct access to the bot
what's the issue?
I started making custom prefix again
import aiosqlite
import discord
from discord.ext import commands
import asyncio
def get_prefix():
pass
bot = commands.Bot(command_prefix='<', intents=discord.Intents.all())
async def connect():
connect = await aiosqlite.connect('prefixes.db')
cursor = await connect.cursor()
await cursor.execute('CREATE TABLE IF NOT EXISTS prefixes(guild_id INTEGER,prefix TEXT)')
await connect.commit()
await connect.close()
@bot.event
async def on_ready():
print("ready")
await connect()
I not able to understand what should be args in get prefix
Btw is my code fine?
At sqlite
I'm totally out since on_ready
Hmmmm
Where to do insted of on_ready?
setup_hook
That's a hard thing for me
Me not able to understand what's use of it
all you have to do is remove connect() from on_ready and do bot.setup_hook = connect ๐
and create a global connection
yes?
How can I create global conn?
async def connect():
bot.conn = await aiosqlite.connect(...)
cursor = await bot.conn.cursor()
await cursor.execute("DO TABLE CREATION CRAP HERE")
await bot.conn.commit()
now bot.conn is global
Is it setup or set
its ctx.author.id
and what is Mod.txt
file txt ...
oo
!d open
open(file, mode='r', buffering=- 1, encoding=None, errors=None, newline=None, closefd=True, opener=None)```
Open *file* and return a corresponding [file object](https://docs.python.org/3/glossary.html#term-file-object). If the file cannot be opened, an [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError "OSError") is raised. See [Reading and Writing Files](https://docs.python.org/3/tutorial/inputoutput.html#tut-files) for more examples of how to use this function.
*file* is a [path-like object](https://docs.python.org/3/glossary.html#term-path-like-object) giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed unless *closefd* is set to `False`.)
yeah wassup
I'm being a dick
lmao got it
Alrr
I wanted to ask if we can use @client.listen() or @client.event and @client.command() because for me the command does not seem to works whenever I try. Tho the event listening is working just fine.
The client is the instance of discord.commands.Bot() and the prefix is also saved in a json file.
on_guild_channel_create is an event, so it will be triggered automatically when that function is decorated with bot.event or bot.listen()
file: main.py
CONFIG_JSON_PATH = "D:\[BOT DISCORDV2.0]\Discord Bot 2.0"
Cog File
how i can import CONFIG_JSON_PATH in my cog file?
from main import CONFIG
ty
i assume you will run the main file?
if yes, then you should put such data in a different file, depending on when you load your cog, you might have a circular import issue
another cog file?
no another file next to ur main file
like utils.py where you have objects which ur cogs might use
so in ur cog u can do from utils import ... and the same thing in ur main.py
ok
channel = await interaction1.guild.create_text_channel(f"mm-{interaction1.user.name}", topic=f"{guild.name} | Request ID: {numbergen}", category=category, overwrites=overwrites)```
error:
```Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 371, in _scheduled_task
await item.callback(interaction)
File "c:\Users\user\Desktop\Ayu Bot\main.py", line 250, in button_callback1
channel = await interaction1.guild.create_text_channel(f"mm-{interaction1.user.name}", topic=f"{guild.name} | Request ID: {numbergen}", category=category, overwrites=overwrites)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\guild.py", line 1170, in create_text_channel
data = await self._create_channel(
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\guild.py", line 1051, in _create_channel
"id": target.id,
AttributeError: 'NoneType' object has no attribute 'id'```
What is category?
category = discord.utils.get(guild.categories, name='mm tickets')
What should be args in get_prefix?
async def get_pre(bot, message):
return "prefix" # or a list, ["pre1","pre2"]
bot = commands.Bot(command_prefix=get_pre ...```
Yo I can help you again in a few hours
Yoo ok
@vocal snow
Make sure it's not None
it isnt
Do you have an assert or if statement?
Would it be possible
To make a discord bot. That with a command. Puts their phone number ( That they would input ) and their discord name & # into a .csv file?
this is above it:
if blacklistrole in interaction1.user.roles:
await interaction1.response.send_message(content="You are **blacklisted**, you cannot create a ticket.", ephemeral=True)
else:```
How are you making sure category is not None though
i dont..
Then do
but id prefer to sort out my error first
and checking if the category is None isnt really useful for what im coding
yes, quite possible
Would it be hard? To make
no
Could I get some help?
!rule 7
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
TIL there is a replit server
Any documentation on how to make discord bots?
check the channel description
I think I should make a starter guide ๐
lucas
I agree
i mean the hikari series is not bad at all other than the token leaks
Hi, im trying to make a discord.py economy bot with some commands, such as a rob command.
I want there to be a cooldown on the rob command, but this cooldown seems to always be activated when I use @commands.cooldown(...), but this is not what I want;
if the robbing fails for whatever reason (not enough arguments, person can not be robbed, etc), I do not want the cooldown to start.
Is this possible?
This pin needs to be updated
didnt even see a single tutorial for hikari so ๐
๐ฟhe wrote a complete bot in hikari
i found his github somehow
Nice
?
Yes that is working for me
but when i am using @bot.command
it does not respond when the command is called
also
@bot.listen()
async def on_message(message):
print(str(message.content))
this is just giving me an empty string
or \n i guess
Did u enabled intents
its not meant to be called automatically when its a command
commands are only called by users
in the commands.Bot() ?
yes and in ur dev page
alright
show the command which is not responding
any command is not responding
this for example
@bot.command()
async def ping(ctx):
await ctx.send(f'Pong! {round(bot.latency * 1000)}ms')
do you have an on_message event
nope, i have an on_guild_channel_create event
How big is this bot?
its a small bot
Could you maybe just paste the whole bot here ->
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.
Leave out the token.
you can even include it if you want us e to use your token
no why, I wanted to use it...... ๐
i use .env for keeping my token lmao
dm me the token pwease
alr
bruh
xD
you need the message_content intent
!intents member_content = True, instead og members= True thats it
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.
Why tho?
read the codeblock
He/she only needs the guild intent for on_guild_channel_create
alright, i have seen it and it worked for me. The issue for this code is the ping command is not working when there is a @bot.listen() specified
But a ping command doesn't use any intents.
and for the ping command? heh
wow panda ;-;
I have a slash bot with 0 intents and can just run a simple ping cmd.
its a normal message comamnd tho?
Yeah true.
which ofc needs message_content intents to work
My mind do be slash
to use prefix commands, the bot needs to read messages, to read messages it needs message_content intent
I just got up okay
๐
show updated code
intents.message_content = True add this
I'm still waiting, just fyi
stop cyber bullying
I'm a kid myself, i should be the one getting bullied here
๐ถ
anyone know how i could send a message in a logs channel when i kick using a command?
code:
@bot.command()
@commands.has_permissions(kick_members=True)
async def kick(ctx, member: discord.Member, *, reason=None):
if reason==None:
reason=" no reason provided"
await ctx.guild.kick(member)
await ctx.send(f'User {member.mention} has been kicked for {reason}',delete_after=3.0)
LOL
i wish i could, i am just finishing up what i am doing rn
but sure
i did dmed you wdym
so just update dpy to the latest github version
getting this error
File "d:\Primary\HawT\main.py", line 58, in <module>
asyncio.run(start())
File "C:\Program Files\Python310\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Program Files\Python310\lib\asyncio\base_events.py", line 646, in run_until_complete
return future.result()
File "d:\Primary\HawT\main.py", line 56, in start
await bot.run(TOKEN)
File "D:\Primary\HawT\venv\lib\site-packages\discord\client.py", line 872, in run
asyncio.run(runner())
File "C:\Program Files\Python310\lib\asyncio\runners.py", line 33, in run
raise RuntimeError(
RuntimeError: asyncio.run() cannot be called from a running event loop
sys:1: RuntimeWarning: coroutine 'Client.run.<locals>.runner' was never awaited```
What are you trying to do?
More specific.
Get all the leaders of the teams?
So all team leaders?
Or anyone with the role "Franchise Owner"?
Does that member have a role with the team name?
So the FO has like "Arizona Cardinals" as a role?
okay I can work with that.
incomplete
@bot.command()
@commands.has_permissions(kick_members=True)
async def kick(ctx, member: discord.Member, *, reason=None):
if reason==None:
reason=" no reason provided"
await ctx.guild.kick(member)
await ctx.send(f'User {member.mention} has been kicked for {reason}',delete_after=3.0)
Hi๐
Two questions, how could i make it send a message to a logs channel when a kick is done? And how could i delete the command usage message?
how to split multiline text in an argument?
i said you can guess
thank you
How to make this?
I need to pass a multiline text to the argument
@bot.slash_command(name="folist")
async def folist(interaction):
teams = [
"Arizona Cardinals", "Atlanta Falcons", "Baltimore Ravens",
"Buffalo Bills", "Carolina Panthers", "Chicago Bears",
"Cincinnati Bengals", "Cleveland Browns", "Dallas Cowboys",
"Denver Broncos", "Detroit Lions", "Green Bay Packers",
"Houston Texans", "Indianapolis Colts", "Jacksonville Jaguars",
"Kansas City Chiefs", "Las Vegas Raiders", "Los Angeles Chargers",
"Los Angeles Rams", "Miami Dolphins", "Minnesota Vikings",
"New England Patriots", "New Orleans Saints", "New York Giants",
"New York Jets", "Philadelphia Eagles", "Pittsburgh Steelers",
"San Francisco 49ers", "Seattle Seahawks", "Tampa Bay Buccaneers",
"Tennessee Titans", "Washington Commanders"
]
fo = nextcord.utils.get(interaction.guild.roles, name="Franchise Owner")
desc = ""
for fomember in fo.members:
team = list(filter(lambda r: True if r.name in teams else False, fomember.roles))[0].name
emoji = nextcord.utils.get(interaction.guild.emojis, name=team.replace(" ", "_"))
desc += f"{emoji} - {fomember.mention} in {team}\n"
embed = nextcord.Embed(
title="Franchise Owners",
colour=0xFFF
description=desc
)
await interaction.send(embed=embed)
edited
The code
I did do It right I thought for a sec it returned a role obj
hmm lambda condition is wrong 1 sec
Try now
I do recommend getting a better solution for it all.
Since it is pretty hard coded at the moment.
Sure how would you like it?
What is rostercap?
does anyone have code for a example of a linkbutton?
@bot.slash_command(name="folist")
async def folist(interaction):
teams = [
"Arizona Cardinals", "Atlanta Falcons", "Baltimore Ravens",
"Buffalo Bills", "Carolina Panthers", "Chicago Bears",
"Cincinnati Bengals", "Cleveland Browns", "Dallas Cowboys",
"Denver Broncos", "Detroit Lions", "Green Bay Packers",
"Houston Texans", "Indianapolis Colts", "Jacksonville Jaguars",
"Kansas City Chiefs", "Las Vegas Raiders", "Los Angeles Chargers",
"Los Angeles Rams", "Miami Dolphins", "Minnesota Vikings",
"New England Patriots", "New Orleans Saints", "New York Giants",
"New York Jets", "Philadelphia Eagles", "Pittsburgh Steelers",
"San Francisco 49ers", "Seattle Seahawks", "Tampa Bay Buccaneers",
"Tennessee Titans", "Washington Commanders"
]
fo = nextcord.utils.get(interaction.guild.roles, name="Franchise Owner")
desc = ""
for fomember in fo.members:
team = list(filter(lambda r: True if r.name in teams else False, fomember.roles))[0].name
member_count = len(nextcord.utils.get(interaction.guild.roles, name=team).members)
emoji = nextcord.utils.get(interaction.guild.emojis, name=team.replace(" ", "_"))
desc += f"{fomember.mention} - {emoji} `{member_count}/24`\n"
embed = nextcord.Embed(
title="Franchise Owners",
colour=0xFFF
description=desc
)
await interaction.send(embed=embed)
How to pass a multiline text to the argument?
text = """
line 1
line 2
line 3
"""
text = "line 1\nline 2\n line 3"
hmm i try
the first one also includes the spaces before the text
!e !e ```py
def pretty_text(text: str) -> str:
return "\n".join([x.strip() for x in text.splitlines()])
print(pretty_text("""
line 1
line 2
line 3
"""))
@cloud dawn :white_check_mark: Your eval job has completed with return code 0.
001 |
002 | line 1
003 | line 2
004 | line 3
Hmm first line is weird doesn't happen on my ide
@bot.command()
async def announce(ctx, channel: discord.TextChannel, *, text=None):
if text==None:
text="no text provided"
await channel.send(f'{text}')
No error or anything, just wont do what its meant to do. Any ideas?๐ค
What is it meant to do?
I'll give you a kiss if you send whole of it
indentation, you have the send inside the conditional, unindent it
ah, thanks
is there a way i can just make it in the ctx.send?
I don't recommend it.
you can interaction.channel.send and interaction.response.defer() but I don't see a point of doing that
its just a one command bot nothing crazy
await ctx.send(embed=embed,veiw=(discord.ui.Button(label='link', url=link)))
trying to do somthing like this
.
๐คฏ
redefining a static value every invocation, but why
I wouldn't even have a list of strings 
same, I'd just place a tuple while calling the filter function
I don't get why people use Role names instead of IDs
IDs are much more convenient
F U N
we're in the discord bots channel, sir
i forgor
is name clashing possible if you use role names?
ofcourse it is
imagine having 2 roles with same names
utils.get will return a list in that case iirc
!d discord.utils.get
discord.utils.get(iterable, /, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.utils.find "discord.utils.find").
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Changed in version 2.0: The `iterable` parameter is now positional-only.
Changed in version 2.0: The `iterable` parameter supports [asynchronous iterable](https://docs.python.org/3/glossary.html#term-asynchronous-iterable "(in Python v3.10)")s...
just make your own custom getter
hehehe code go brrrrrrrr
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
there's already a commands.RoleConverter
jUsT uSe sLaSh
indeed
code:
https://paste.pythondiscord.com/ofakiwilun
error:
Bot is ready!
Waiting For Commands
Ignoring exception in command download:
Traceback (most recent call last):
File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\core.py", line 172, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\Andy\PycharmProjects\WhiskeyBotMain\cogs\youtube.py", line 42, in download
file_size = os.stat(f"{file_name}").st_size
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: "I Built The World's Tallest Dice Tower (But Does It Survive?!).mp4"```
!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)
ah ok
it's a ytdl error though not a discord bot related or ffmpeg
It's neither.
panda you so smart ๐
Can't tell if sarcasm or not ๐
if I say that's sarcastic you're gonna be offended
either way sucks works
Also why are you trying to play the audio of a non song
One Library Ik u might need can be datetime
hi
i made a command
@bot.command()
async def hi(ctx, *, args=None):
if args != None:
members = ctx.guild.members
for member in members:
print(member)```
but it just prints the name of the dc bot
and not of eg me
A reminder bot written in discord.py. Contribute to DoggieLicc/ReminderFriend development by creating an account on GitHub.
Check this
You need member intents
tried adding
intents.typing = False
intents.presences = False```
but still dont work
Have you enabled them in the application webpage
You didnโt enable the member intents
๐
intents.members = True
what is the difference between ctx.send() and ctx.channel.send()?
Same thing
#ban command
@bot.command()
@commands.has_permissions(ban_members=True)
async def ban(ctx, member: discord.Member, *, reason=None):
LogsChannel = discord.utils.get(ctx.guild.channels, name="logs")
if reason==None:
reason="no reason provided"
await ctx.message.delete()
await ctx.guild.ban(member)
await ctx.send(f'User {member.mention} has been banned. Reason: {reason}',delete_after=3.0)
await LogsChannel.send(f"{member.mention} has been banned. Reason: {reason}")
Do you know how i could dm the user being banned?
!d discord.Member.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
keep in mind that the user's privacy & safety options may block your dm
yeah, thought about that but oh well๐
so before the ban i should put: await send(content)
or does it have to be all of that๐ง
Yes
private
No
Hey, does anyone have a idea to do a check for this?
im not sure if im dumb but, for all my commands i need to a check if the userdict dosnt exist, it makes it because i have checks in the start of the command that need to check the dict. if i ever edit the dict tho ill have to gothru every single command and edit where it makes the dict
is there any way i can just have a single check for all cmds(slash) and if it dosnt exist it would just maybe like, return a msg saying run the cmd again & during that it makes the dict? idk haha
Make a command decorator for it
Why is it that I get an "Invalid two-factor code" when I try to invite my bot to my server?
Not Python related but I just need help with ma Discord bot
Unrelated so I will not help you ( not that I donโt have a clue how to help you haha ๐ )
'Unindent does not match any outer indentation level' ๐ง
The "await"s don't line up
I could be wrong but I think that's why
Yeah thereโs a indent
Like how you have two "await", I'm pretty sure it's supposed to line up
Fr you gotta get rid of dat shit bruh ๐
That shit'll fuck up your code frfr
member.send()
!d discord.Member.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
wdym by this
Make a decorator
๐
๐ฏ
This ainโt even discord.py related
is there a way to add discord user variable to on_button_click event?
Get the discord member who clicked the button?
this is interaction.author
i want a discord user
like the parameter for command (user:discord.User)
Oh
You can add a drop down view with all server members
Or an input view
Button is purely a clickable button
with open('voice.json', 'r') as file:
voice_data = json.load(file)
new_user = str(member.id)
# Update existing user
if new_user in voice_data:
voice_leave_time = int(datetime.datetime.now().timestamp())
voice_join_time = voice_data[new_user]
calculate_time = (
datetime.datetime.timestamp(voice_leave_time) - datetime.datetime.timestamp(
voice_join_time))
voice_data[new_user] = f'{calculate_time}'
with open('voice.json', 'w') as update_user_data:
json.dump(voice_data, update_user_data, indent=4)
# Add new user
else:
new_voice_join_time = int(datetime.datetime.now().timestamp())
voice_data[new_user] = new_voice_join_time
with open('voice.json', 'w') as new_user_data:
json.dump(voice_data, new_user_data, indent=4)```
did you know?
you can't use datetime.datetime.timestamp like that. You can probably just do voice_leave_time - voice_join_time
its working but its str..
thats because you are putting it in an f string. voice_data[new_user] = f'{calculate_time}' you can just do voice_data[new_user] = calculate_time
oh ok
For some reason when I try to import praw, project can't find it
but I installed it using cmd
pls help
#โ๏ฝhow-to-get-help
wrong channel
to make a leave command, how would i write the guild id inside of the parentheses??
async def leave(ctx, ):
what do i put after ctx?
so i can put the id of the server to leave and the bot will leave
?
Anything you want really.
i dont know if you saw my other messages but im asking what is the ID for the server defined as
its not guild.id
Yeah I get what you mean
What would be the best way to delete all the messages from a specific user in a channel
Manually go through them and delete them
that definitely is not the best way
If I wanted to ban someone if they try to change the guild icon how would I go about that?
Like a trigger?
!d discord.TextChannel.purge
await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=None, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.
You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own. The [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.
Changed in version 2.0: The `reason` keyword-only parameter was added.
Examples
Deleting botโs messages...
Like when they change it it automatically bans them?
yeah like that
I have no idea brother, that has to do with the audit logs prolly
Which I have absolutely no idea how to tamper with
all good
you can just type hint with disnake.Guild
I don't know what that means
I'm trying to compile a list of the guild ID's that my bot is in
the question is why does someone have permissions to change the icon in the first place
that is exposed as bot.guilds
@bot.command()
async def leave(ctx):
toleave = bot.get_server("id")
await bot.leave_server(toleave)
This is my code, and rigth after "ctx," I need to write whatever "guild ID" is
@bot.command()
async def servers(ctx):
activeservers = bot.guilds
for guild in activeservers:
await ctx.send(guild.name)
print(guild.name)
nvm I got it
This is my code to compile all of the servers, what I need help with is to put the ID's of the servers next to the servers name on the list that my bot makes, and then for the "leave" command I need to be able to put the guild ID after "leave" and have my bot leave that server
can you change the guild icon using guild.edit?
Nevermind I figured it out on my own lol
It only took 2 and a half hours
@tasks.loop(seconds=5)
async def randommessage():
channel = client.get_channel(994367892000870421)
await channel.send("test")
For some reason this doesn't send the word "Test" in that channel every 5 seconds
How can this be fixed?
did you start the task?
no
would that be randommessage.start()?
Yesn't
Unhandled exception in internal background task 'randommessage'.
Traceback (most recent call last):
File "C:\Users\rscdo\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\tasks\__init__.py", line 101, in _loop
await self.coro(*args, **kwargs)
File "main.py", line 18, in randommessage
await channel.send("test")
AttributeError: 'NoneType' object has no attribute 'send'
I got this error when the program started
Fetch the channel.
i did there...
You can't
You can make a custom check for it but it will be visible.
Pretty sure that is get and not fetch
ok lemme fix dat
I recommend getting it first else fetch
so like await client.fetch_channel(994367892000870421)
how will it be visible? like when I type / and click on the bot that there is shown: you have no permissions?
@bot.command()
@commands.is_owner()
async def leave(ctx, guild_id, *, self):
guild = discord.utils.get(self.bot.guilds, name=guild_id)
if guild is None:
await ctx.send("I am not in that server")
return
await self.bot.leave_guild(guild)
await ctx.send(f"I am no longer in {guild.name} ({guild.id})!")
What's wrong with my code?
No he/she can also use it but you will need to say as response they cannot use it.
My issue is that when I try to execute the command, I have to also put the "self" when trying to use the command
How do I not have that issue?
You copied it.
Copied what?
@tasks.loop(seconds=5)
async def randommessage():
channel = client.fetch_channel(994367892000870421)
await channel.send("test")
randommessage.start()```
like dis?
await it
ok
@tasks.loop(seconds=5)
async def randommessage():
await client.wait_until_ready()
channel = client.get_channel(994367892000870421) or await client.fetch_channel(994367892000870421)
await channel.send("test")
randommessage.start()
ok lemme try it out
but then with await channel isnt defined
itโs definitely somehow possible since that happened to me. I cant use the commands anymore in any server.
So can you help me or not?
anyone know where to upload long lines of codes?
from discord import HTTPException, Guild
@bot.command()
@commands.is_owner()
async def leave(ctx, guild_id: Guild | None = None) -> None:
if not guild_id:
return await ctx.send(f"I can't find: {guild_id}")
try:
await guild.leave()
except HTTPException:
return await ctx.send(f"Something went wrong try to leave {guild_id}")
await ctx.send(f"I am no longer in {guild.name} ({guild.id})!")
i need help with something but dont wanna flood chat
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
What bot is this?
What's this?
i have my token in there but it gives me this error
A proper leave command.
๐
If a guild has a vanity link how do i get it? is it guild.vanity_url ?
not public
Did you load the env?
Preciate it, most people would yell at me and throw a tantrum about "spoonfeeding"
You a real one ๐
no. im using some youtube tut thing for playing music in just my server but seems as i get error ffmpeg isnt found so im trying another code and idk anyhting about cog
and since Iโve never seen that before that this is possible, I wanna know how to do it
Well I do recommend programming it on your own but you went the whole other way with this command.
Oh sorry but we don't help with music bots here.
Hmm could you give a bigger screenshot with greyed out command or anything?
That's my problem lmao, I had 0 guidance and I programmed all of the rest of the bot myself but I'm still new to discord bots
Thank you lots ๐
you should be happy people do, theirs a reason why people do it and its encouraging you to learn, thats not a bad thing.
thatโs literally everything. there is just the name and nothing more. I cant even see the commands
https://discord.com/developers/docs/interactions/application-commands#permissions
"Application command permissions allow your app to enable or disable commands for up to 100 users, roles, and channels within a guild."
im pretty sure thats the whole purpose of the server, encouraging people to learn python
Agreed, I got muted for an hour when I asked if someone could help with my code last time I was in this discord lol
How could i make this loop work?py @client.command() async def test(ctx): await ctx.send("Test completed! I work!") @tasks.loop(seconds=5) async def randommessage(ctx): print("Test message request recieved!") await ctx.send("Test completed! I work!") randommessage.start()
well sometimes people do say for no reason "we wont spoonfeed you" at that point i would just ignore them lmao
Well you don't just get muted for that.
anyway to retrieve guild vanity?
sometimes backing away from a discussion is needed to stop it from starting an argument
!d discord.Guild.vanity_url_code
The guildโs vanity url code, if any
New in version 2.0.
!d discord.Guild.vanity_invite
await vanity_invite()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Returns the guildโs special vanity invite.
The guild must have `VANITY_URL` in [`features`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.features "discord.Guild.features").
You must have the [`manage_guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_guild "discord.Permissions.manage_guild") permission to use this as well.
mhm in disnake you can use the use_cacheto convert vanity_url_code to the full invite, thats cool
Well to be fair when sarth was helping someone you did just gave away the whole answer to someone.
This command gives me this error on file startup:
@client.command()
async def test(ctx):
await ctx.send("Test completed! I work!")
@tasks.loop(seconds=5)
async def randommessage(ctx):
print("Test message request recieved!")
await ctx.send("Test completed! I work!")
randommessage.start()``````Traceback (most recent call last):
File "nitro.py", line 15, in <module>
async def test(ctx):
File "C:\Users\rscdo\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 1263, in decorator
self.add_command(result)
File "C:\Users\rscdo\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 1149, in add_command
raise CommandRegistrationError(command.name)
discord.ext.commands.errors.CommandRegistrationError: The command test is already an existing command or alias.```How can this be fixed
Not have 2 command with the name test
i want the loop to happen once the command is executed tho
and in the channel that its executed
so that it can be multiple channels at once
hello not related to music at all but ffmpeg was not found but i have done pip install ffmpeg-python
and its already installed
That seems pretty related to music lol
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)
u can use this. coded this a few weeks ago. should work ig if its the right code
@tasks.loop(minutes=5)
async def hello():
channels = [437680309824258060] # List of channels
for ch in channels:
channel_to_send = client.get_channel(ch)
await channel_to_send.send("a")```
alright alright
that screams NoneType attribute errors lol
gave me this error AttributeError: 'NoneType' object has no attribute 'send'
hehe i called it
oh shi
lmao
er we go await client.wait_until_ready() fixed it
and I said if its the right code. had this in my server, so might be the wrong one idk
you would still need to add a check to that loop even if its in your server
"Traceback (most recent call last):
File "main.py", line 729, in <module>
async def leave(ctx, guild_i
Traceback (most recent call last):
File "main.py", line 729, in <module>
async def leave(ctx, guild_id: Guild | None = None) -> None:
TypeError: unsupported operand type(s) for |: 'type' and 'NoneType'"
@bot.command()
@commands.is_owner()
async def leave(ctx, guild_id: Guild | None = None) -> None:
if not guild_id:
return await ctx.send(f"I can't find: {guild_id}")
try:
await guild.leave()
except HTTPException:
return await ctx.send(f"Something went wrong trying to leave {guild_name}")
await ctx.send(f"I am no longer in {ctx.guild.name} ({ctx.guild.id})!")
@cloud dawn Sorry to ping you, but I get this error when I run your code
panda what is that example
You need py 3.10 to use |
Oh thanks for teaching me kappa
my pleasure
wish u were that good to stay in udevs 
im too good to be in that dead server
Whats an Union okimii
ive only heard about an onion
@bot.command()
@commands.is_owner()
async def leave(ctx, guild_id):
if not guild_id:
return await ctx.send(f"I can't find {ctx.guild_name}")
try:
await ctx.guild.leave()
except HTTPException:
return await ctx.send(f"Something went wrong trying to leave {ctx.guild_name}")
await ctx.send(f"I am no longer in {ctx.guild.name} ({ctx.guild.id})!")
Now my bot just doesn't work
Like any commands
Nevermind, somehow the leave command made the bot leave the server I was testing it in haha
Well it works kinda
So now when I leave, even when I put another guilds ID, it just leaves the discord that I'm using the command in
OHHHHH
kai going beast mode
So what do I do about that?
ask coding god okimii
arent you in the elite professional udevs dead server๐
ask kai hes in an epic legendary elite professional dev ops team named udevs๐
Well I don't care who helps me I just need help lol
okimii seems abit mad over me 
you need to get the guild you provided the id with then use the leave() method
So do I get rid of ctx?
yeah im so so sad and mad im not in the epic legendary elite professional dev ops team named udevs๐
guild = self.bot.get_guild(guild_id)
await guild.leave()
well since its not within a cog just do bot.get_guild(guild_id)
no code block๐
It still says "Undefined name 'guild_name'"
because thats not a valid attr afaik
cuz of this if not guild_id: return await ctx.send(f"I can't find {ctx.guild_name}")
So I should get rid of that?
except HTTPException:
return await ctx.send(f"Something went wrong trying to leave {ctx.guild_name}")
this too
So do I get rid of both of those things?
you want to make guild_id optional?
Wdym?
I just want the command to be where I do "!leave [guild ID here]"
And then it leaves the server that I put the ID for
No
I don't wanna make it optional
Sorry I just got what you meant lol
๐ฟ
Then you don't need the first check and in the exception you can change ctx.guild_name to ctx.guild
What first check?
And would ctx.guild make the bot leave the server that I did the command in?
yup
it can return an instance of a discord.Guild object
I don't know what that means homie
its the same thing bro
You create instance/objects from a class kek
you make no sense
Sooooooooooo how do I define the guild name
Or how do I define the said guild that I want to leave
<discord.embeds.Embed object at 0x000001C0CC3DA940>
I get that when i send my embed
embed = discord.Embed(title=":rotating_light: alert", description="**New word incoming!**",color=0xfd00c2)
embed.set_thumbnail(url="--")
``` How can I fix dis
You can fix it by waiting patiently for someone to help you and not sending it a 2nd time
you tried to print the obj lol
wdym?
Instance is an object that belongs to a class. okimii plz
Can you send it using the backticks and discord.py?
an instance is an instance of an initiated class bro
uhm i mean i just did await channel_to_send.send(embed) to send it
@bot.command()
@commands.is_owner()
async def leave(ctx, guild_id):
guild = bot.get_guild(guild_id)
try:
await guild.leave()
except HTTPException:
return await ctx.send(f"Something went wrong trying to leave {ctx.guild}")
await ctx.send(f"I am no longer in {guild} ({guild.id})!")
@crude crater
nice one
that one too
Fanks
Trying to spit on a code i just copy pasted directly from him 
your discussion had no point compared to mine lmao
Okimii come dm u need to learn some more
so you just copy it and slap it in the chat
No one cares about your flex tries when you dont even know what ure talking about
oh i bet i need to learn python again๐
flex?
This still doesn't work
No error, and the command is on my help list
But when I use it how it's intended, NOTHING happens
No error, nothing
its because the guild_id wasnt converted to an int
type hint it with an int guild_id: int
How do I do that?
Where do I put this?
in your command params
in your parameters
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Guild' object has no attribute 'icon_url'
do icon.url
alr
Thank you so much!!! I literally love you
discord.py 2.00 broo
Mwah!! :*
i never know what im doing ๐
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'url'
FOR REAL
yeah in dpy 2.0 icon is an Asset obj
it returns None
but im sending the cmd in a guild 
its not the guild
oh shit is it bc ion have a server pfp
!d discord.Guild.icon
property icon```
Returns the guildโs icon asset, if available.
if available.
alr ima make a error handler LOL
tyty tho 
you're welcome :))
im used to older discord.py 
๐
im using subfolders bc im weird 
oof thats allot of files, maybe you can use cogs and order each command by their category in a cog e.g Moderation only commands
yeah, i could do that but i like it this way bc idk im just different yk what im saying 
i get you, do what your heart desires its your code at the end of the dayโค๏ธ
Yes
:))
f
@commands.command(aliases=['s'])
@commands.has_any_role('Dj','dj','DJ')
async def skip(self, ctx):
player = self.bot.lavalink.player_manager.get(ctx.guild.id)
if player.is_playing:
if ctx.author.guild_permissions.manage_guild or ctx.author.id == player.current.requester or ctx.author.guild_permissions.administrator or ctx.author:
await ctx.message.add_reaction("โญ๏ธ")
await player.skip()```
is there a way to check if the author has a role using this 1 liner `if ctx.author.guild_permissions.manage_guild or ctx.author.id == player.current.requester or ctx.author.guild_permissions.administrator or ctx.author:`
making a music bot and want the song requester or a dj to be able to skip
why this happening?
out of no where discord.utils and discord.ext.commands are underlined red
'Guild' object has no attribute 'vanity_url_code'
you're most likely in pre-2.0 then
you would be using discord.Guild.vanity_invite ( which is a coroutine ) since you're on 1.7.3
anyone know for this?
can you hover on it and see what the warning says?
i have it installed pip
average person who used discord.js
I appreciate it, cheers!
ImportError: cannot import name 'commands' from 'discord.ext' (unknown location)
and theres this in console
nvm got it
@bot.command()
async def serverinfo(ctx):
embed = discord.Embed(title=f"{ctx.guild.name} Info", description="Information of this Server", color=discord.Colour.blue())
embed.add_field(name='๐Server ID', value=f"{ctx.guild.id}", inline=True)
embed.add_field(name='๐Created On', value=ctx.guild.created_at.strftime("%b %d %Y"), inline=True)
embed.add_field(name='๐Owner', value=f"{ctx.guild.owner.mention}", inline=True)
embed.add_field(name='๐ฅMembers', value=f'{ctx.guild.member_count} Members', inline=True)
embed.add_field(name='๐ฌChannels', value=f'{len(ctx.guild.text_channels)} Text | {len(ctx.guild.voice_channels)} Voice', inline=True)
embed.add_field(name='๐Region', value=f'{ctx.guild.region}', inline=True)
embed.set_thumbnail(url=ctx.guild.icon_url)
embed.set_author(name=f'{ctx.author.name}' icon_url=ctx.message.author.avatar_url
await ctx.send(embed=embed)
It says "icon_url=ctx.message.author.avatar_url" has an invalid syntax
How I fix?
Okay nevermind I just got rid of those 2 last lines
You forgot a comma
@bot.command()
async def serverinfo(ctx):
embed = discord.Embed(title=f"{ctx.guild.name} Info", description="Information of this Server", color=discord.Colour.blue())
embed.add_field(name='๐Server ID', value=f"{ctx.guild.id}", inline=True)
embed.add_field(name='๐Created On', value=ctx.guild.created_at.strftime("%b %d %Y"), inline=True)
embed.add_field(name='๐Owner', value=f"{ctx.guild.owner.mention}", inline=True)
embed.add_field(name='๐ฅMembers', value=f'{ctx.guild.member_count} Members', inline=True)
embed.add_field(name='๐ฌChannels', value=f'{len(ctx.guild.text_channels)} Text | {len(ctx.guild.voice_channels)} Voice', inline=True)
embed.add_field(name='๐Region', value=f'{ctx.guild.region}', inline=True)
embed.set_thumbnail(url=ctx.guild.icon_url)
await ctx.send(embed=embed)
Now this doesn't work
Where?
In embed.set_author
After the name kwarg
Well either way I got rid of that code but now my new code doesn't work, do you mind helping me with that?
It's cool if not it's kinda a pain lmao
Whatโs the error
I want it to send the embed?
I don't think so
Huh then Iโm not sure why itโs not sending
๐คทโโ๏ธ
ah i didnt see that there
maybe you need to edit it too?
colour = discord.Colour.random()
no no, you just need to actually make an instance over making variables!
alr it works now but i also am putting in the gif but the gif just seems to keep loading?
nah they have a comma there, so it will mak a tuple
i think they want
discord.Embed(
color = ...,
description = ...
)
actually?
nah i didnt mean to put a coma there
!e
a = 1,
print(a)
@paper sluice :white_check_mark: Your eval job has completed with return code 0.
(1,)
ah thats kinda funny
but description is still a variable
ยฏ_(ใ)_/ยฏ
ya, they wanted to pass it directly into the constructor
anyone know why it just endlessly loads tho?
yup yup
@slate swan do this ^^
the link needs to directly reference the gif, so in the tenor page you'd right click the actual gif and select "Copy image address" then use that
yea i got it to wrok
Looks like the ModMail bot isn't working "Your message could not be delivered. This is usually because you don't share a server with the recipient or the recipient is only accepting direct messages from friends. You can see the full list of reasons here:"
Obviously we share a server since I'm well typing here, lol
do you have direct messages off?
in this server's settings
right click the server icon -> privacy settings -> allow direct messages from server members
make sure it's set to on
Oh nice, I didn't know you could change that per server, thanks! @slate swan
ello again im making the command hack like so that dank has and when i do random.choices(names) it shows this
jut for these two
they arent defined?
Is it not possible to do a f string inside a f string??
fStuff f'hello' if x not true else f'lol
i get a error when i try
thats a horiable example one sec
oh wait, it's cause the usage of double quotes inside double quoted strings, use single quotes
!e
a = None
print(f"Hello {a or 'World!'}")
@slate swan :white_check_mark: Your eval job has completed with return code 0.
Hello World!
!e
n = "Ash"
s = f"Heck you, {f'{n}'}"
print(s)```
@slate swan :white_check_mark: Your eval job has completed with return code 0.
Heck you, Ash
why would you do that ๐
like making them
this umbrella on my head it making me do it ๐ฉ
do it๐ณ
just examples
im making copilot write js for me, cuz i will never write that lang myself
https://Rehold.is-watching-you.xyz/iZa5cjU2
Not sure if im tired or what ๐ญ, ive been working on this for like hours straight now
yeah i have
trying to a check if theres a role in the db, it shows the role. else it shows "Not Set"
youre lucky you know js for uis๐
use double/triple quotes, dont use the same quotes you initiated the string with
react ftw
๐คจ
i tried this
same thing
but I dont mind writing pure html and css, I love html ๐
html and js part of this is the one i dont like
ryuga ew
ikr๐ ๐ญ
in my defence, copilot wrote the right side, idk any html or js
why would you write js inside html, you monster ๐ญ
most people do it
that is why copilot recommended that 
damn you really hate me๐
๐ณ
everywhere i go, i see ๐งข
all you see is yourself
๐ณ
never
i used ws with aiohttp now im using wss
alr
I've never used websockets with python rip
no wait only once
I feel ryuga
โ๏ธ
I still wonder why the qm is after the em
for that emoji*
you had one job copilot
why even typehint soomething that's already been typehinted anyways
and I hate how i cant shift enter and have to manually change binds in the settings
sometimes you define new class attrs, and then you add that in constructor and type hint it, so for consistency, i do it for all vars in init
I'm already out, you have a github repo for the bot?
yea? its just private
hm
https://github.com/RyugaXhypeR/Reddit-Meme-Scrapper
but why a "scrapper" and not "scraper" ๐ญ
ughhh im so lot if anyone can help... ive been stuck for like 6 hours
import discord
from time import sleep
import asyncio
import tweepy
discord_token = 'discord_token'
access_token_secret = 'access_token_secret'
access_token = 'access_token'
consumer_secret = 'consumer_secret'
consumer_key = 'consumer_key'
auth=tweepy.OAuthHandler(consumer_key,consumer_secret)
auth.set_access_token(access_token,access_token_secret)
api = tweepy.API(auth)
client=discord.Client()
discord_channel_id='MY_CHANNEL_ID'
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
sleep(0.5)
print('BOt is Ready!')
@client.event
async def on_message(message):
if message.author != client.user and str(message.channel.id) ==discord_channel_id :
api.update_status(status=message.content)
async def main_func():
await client.start(discord_token)
asyncio.get_event_loop().run_until_complete(main_func())```
For some reason no matter how many times i reset the tokens or api keys for my bot or for twitter api to connect with tweepy it keeps giving me a invalid token passed for line 29 wich would be `api.update_status(status=message.content)` meaning its a twitter api key.... i have reset and verified mutiple times they are correct and also have the correct read & **write** auth on
thanks in advance for any help
discord bot but using tweepy to autopost discord messages
bot connects, can even get a print in console but when i send a message i get error code for line 29 api.update_status(status=message.content) saying
tweepy.errors.Unauthorized: 401 Unauthorized 89 - Invalid or expired token.
you have not properly authorized tweepy
maybe invalid token?
token is correct 1000000%
try to reset
ivve reset it and even tried a second account with elevated access, auth 1.0 ,2.0 ... deleted and created a new bot
ive tried everything litterly
wat do you mean authorize tweepy?
i mean the error says it
providing the tokens
well the error is wrong lol
ยฏ_(ใ)_/ยฏ
ive checked the token
tokens** mutipkle times
discord_token = 'discord_token'
access_token_secret = 'access_token_secret'
access_token = 'access_token'
consumer_secret = 'consumer_secret'
consumer_key = 'consumer_key'```
these are the tokens asked for
discord worked as the bot comes online, and responds
api token secret - checked and even reentered
api token - checked and even reentered
consumer secret - checked and even reentered
consumer key - checked and even reentered
anything else you suggest lol
did you properly save the script and re-run it?
ive deleted the bot, gave it auth 1.0, 2.0 as well as tried it on my acct with elevated api access and still same response
yes , ive actually deleted it all and restarted
ive been wroking on this for like 6 hours lol
never does it take me this long to write and run 40 lines ๐คฃ
off topic but what is this theme called?
vuesion theme + background image
๐
am I the only one who only sees the image but not the text
yes
looks like emacs
but ryuga is using pycharm currently so idk
anyone got good command recommendations to add?
i would love to use emacs, but it doesn't work well with windows, so no
its pycharm
sed
ofc
pycharm Professionalโข๏ธ
nah, i had the same setup in community as well
im gonna dual boot my pc with arch then use emacs
just use wsl
no ty
wsl sucks, and im not going to upgrade to win11 to use wslg
๐
Ig response = await request(...) why would you use with statement ๐ฉ
You just didn't get to colors, pycharm's color scheme is pretty well customizable
idk how to do anything with urls
The request function probably isn't a coroutine
import requests
import asyncio
async def main():
async with requests as req:
async with req.request(...) as response:
async with response.json() as content:
async with content as con:
print(con)
asyncio.run(main())
uwuwuwuwu
Heck
I wanna cry after what I just wrote
Go get some coffee... And ketamine
tea >> coffee
and I guess I will ๐
requests is a sync lib, what are you doing 
why are you even correcting that code
to make it look cursed smh
i just hoped on and saw that
lmao
cursed != errors
like I care

can anyone explain how i could read select outputs from a embed
needing the description and the image... below i have only tried description but any help thanks
@client.event
async def on_message(message):
if message.author != client.user and str(message.channel.id) ==discord_channel_id :
embed = message.embeds
api.update_status(status=embed.description)
print('done')
I got this that works, but only for messages.. im trying to read a embed and only output description and image
@client.event
async def on_message(message):
if message.author != client.user and str(message.channel.id) ==discord_channel_id :
api.update_status(status=message.content)
print('done')
Does anyone here made a bot that also connected with whatsapp?
!d discord.Message.embeds returns a list of embeds. You need to index the embed also
A list of embeds the message has. If Intents.message_content is not enabled this will always be an empty list unless the bot is mentioned or the message is a direct message.
soo something like this ?? api.update_status(status=discord.Message.embeds(title, description, image_url)) i understand that part i just caint seem to get this part
No
first of all we don't even know what that api is, but you don't even need that, once you have the embed object you can modify it and then modify the message where that embed is attached to
assuming i need something like this
embed_dict = embed.to_dict()
and i need to get
description
image or image url
You can access those with the embed object 
hey i made a slash command which just simply adds a role to the user using application checks
@client.slash_command(name="vaddrole", description="adds a role to a user")
@application_checks.has_permissions(administrator=True)
async def addrole(interaction: nextcord.Interaction, member: nextcord.Member, role: nextcord.Role):
but now i want to send an error message to the user who doesnt have the perms
how to do that ??
!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 logs to the library logger, however it could be overridden to have a different implementation.
This only fires if you do not specify any listeners for command error.
Changed in version 2.0: `context` and `exception` parameters are now positional-only. Instead of writing to `sys.stderr` this now uses the library logger.
i tried making an event
@addrole.error
async def on_application_command_error(interaction, error):
if isinstance(error, commands.MissingPermissions):
await interaction.response.send_message(f"You lack perms", ephemeral=True)
and it doesnt send the reply
what is that application_checks?
it doesn't raise missing permission, read the docs again
!d nextcord.ext.application_checks.has_permissions
@nextcord.ext.application_checks.has_permissions(**perms)```
A [`check()`](https://nextcord.readthedocs.io/en/latest/ext/application_checks/index.html#nextcord.ext.application_checks.check "nextcord.ext.application_checks.check") that is added that checks if the member has all of the permissions necessary.
Note that this check operates on the current channel permissions, not the guild wide permissions.
The permissions passed in must be exactly like the properties shown under [`nextcord.Permissions`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Permissions "nextcord.Permissions").
This check raises a special exception, [`ApplicationMissingPermissions`](https://nextcord.readthedocs.io/en/latest/ext/application_checks/index.html#nextcord.ext.application_checks.ApplicationMissingPermissions "nextcord.ext.application_checks.ApplicationMissingPermissions") that is inherited from [`ApplicationCheckFailure`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.ApplicationCheckFailure "nextcord.ApplicationCheckFailure").
If this check is called in a DM context, it will raise an exception, [`ApplicationNoPrivateMessage`](https://nextcord.readthedocs.io/en/latest/ext/application_checks/index.html#nextcord.ext.application_checks.ApplicationNoPrivateMessage "nextcord.ext.application_checks.ApplicationNoPrivateMessage").
so i should use
@command.has_permissions
instead ?
It depends if application commands inherits from commands 
but why you should rewrite the entire command
just change the isinstance 
shows undefined name 'command'
command or commands?
Huh show code
you should, otherwise python will curse you with syntax errors irl.
I'm already dead idk
Bruh literally you had only to change the class in the isinstance method 
i do need that, its twitter api call for developer portal through the discord bot... this is where im calling the api keys and updating a tweet
i just caint figure out how to read the embed readout as im sending tweets every time a embed posted.... so im just looking for something like this i suppose
api.update_status(status=discord.Message.embeds(description, url_title))
Hello, does someone know why when I try to set an image in an embed message it looks like this ?
@app_commands.command(name="image", description="Send a random image")
async def image(self, interaction):
link = SCREENSHOT_URL + ''.join(random.choice(string.ascii_lowercase + string.digits) for i in range(6))
embed = discord.Embed(color=0xda8607)
embed.set_image(url=link)
await interaction.response.send_message(embed=embed)
When I'm using the link there is an image, but it is not displayed.
the image doesnt exist prolly
When I click on the preview and open the original image, there is an image
The same thing but not in an embed message works but on in an embed
Hi ash
hi
seems like discord cant process it
Me not able to understand how to write the get_prefix function
nice
import os
from discord.ext import commands
DISCORD_BOT_TOKEN = os.getenv("DISCORD_BOT_TOKEN")
bot = commands.Bot(command_prefix="!")
for filename in os.listdir("./cogs"):
if filename.endswith(".py") and filename != "init.py":
bot.load_extension(f'cogs.{filename[:-3]}')
print(DISCORD_BOT_TOKEN)
does someone by any chance know why pycharm doesnt read my bots token in the .env file?
thought i did it right apparently not since the print shows: none
๐ง
just create a function that takes bot and messages parameters and make the function return a string/iterable of strings, and set the command_prefix=prefix_func_name
I wanted to ask that whats use of bot in it?
Oh k
def prefix(_bot: commands.Bot, message: discord.Message) -> ...:
...
remove the _ if you will use it
which you probably will to access the db connection
How can we get message guild I'd?
you need to use python-dotenv to read environment variables
a .env file is no different from a text file
message.guild.id
from typing import Any
class MyBot(commands.Bot):
def __init__(self) -> None:
super().__init__(command_prefix=self.get_pre, intents=intents)
self.prefixes = {}
def get_pre(self, bot: commands.Bot, message: discord.Message) -> Any:
return self.prefixes.get(message.guild.id, "!")
something like that
!pypi python-dotenv
already installed and its in the root file too but my pycharm just isn't able to ready it somehow
you need to load the env too
How to select guild I'd and get prefix?
dotenv.load_dotenv()
you need to add this to your code ```py
from dotenv import load_dotenv # install the python-dotenv package
load_dotenv() # take environment variables from .env```
rip
put it at the start
huh? you need to install that, i thought it was builtin
u have to provide path for the .env file as well
omg ye i just saw in the docs u guys are amazing thanks
no lmao
pip install python-dotenv
How to select guild I'd and get prefix?
I don't even need this library most of the times,my .envs work fine without loading manually
nope isn't builtin
i never installed it, probably it got installed by some other package
maybe, just use pip show python-dotenv and check the required by field
store id as key and prefix as value, easy
Bro i not mean the guild id
^^
No i mean how to fetch it from db?
anyways, .yaml ftw
do the same thing, just instead of a dict, get values from the db
I asking how to
use .txt and make your own obscure parser \s
that depends on like 3-4 things
what database you are using
whats your data format structure
and the data type you use for keys/fields
Sqlite
cur.execute("SELECT prefix FROM table WHERE id=?", {guild.id})
prefix = cur.fetchone()
this should work, i haven't worked with sqlite for a long long time
And guild _id is int and prefix is str
def get_prefix(Bot, message):
bot.connect = await aiosqlite.connect('prefixes.db')
cursor = await bot.connect.cursor()
id = message.guild.id
await cursor.execute('SELECT prefix FROM prefixes where guild_id=?',{id})
prefix = await cursor.fetchone()
return prefix
Is it correct?
that was a vague solution, you need to create a table with id an prefix columns first
That's already done in setup hook
once you create the table, you store the id and prefix then you can get it using that
then run it and see ๐ณ
don't create so many connections
ya connect in the setup_hook itself
And will it be prefix=get_prefix or prefix=get_prefix()
you're literally making a new connection everytime someone sends a message and not even closing iy
command_prefix=get_prefix
I closed it in hook
but not in the get_prefix
or do this
async def main():
async with bot:
async with aiosqlite.connect(...) as connection:
bot.connection = connection
await bot.start()
and then use bot.connection
import aiosqlite
import discord
from discord.ext import commands
import asyncio
def get_prefix(Bot, message):
connect = await aiosqlite.connect('prefixes.db')
cursor = await connect.cursor()
id = message.guild.id
await cursor.execute('SELECT prefix FROM prefixes where guild_id=?',{id})
prefix = await cursor.fetchone()
if prefix:
return prefix
else:
return '~'
await connect.commit()
await connect.close()
bot = commands.Bot(command_prefix=get_prefix, intents=discord.Intents.all())
async def connect():
bot.connect = await aiosqlite.connect('prefixes.db')
cursor = await bot.connect.cursor()
await cursor.execute('CREATE TABLE IF NOT EXISTS prefixes(guild_id INTEGER,prefix TEXT)')
await bot.connect.commit()
await bot.connect.close()
bot.setup_hook = connect
@bot.event
async def on_ready():
print("ready")
Is it fine?
why don't people use cm where it can be used ๐
What cm
contextmanager
Anyway it's fine for my level
there is nothing complicated about it
!e
class Foo:
def __enter__(self, *a): # i dont remember what args they took
print('enter')
def __exit__(self, *a):
print('exit')
with Foo() as f:
print('inside')
with Foo() as f:
raise Exception()
@paper sluice :x: Your eval job has completed with return code 1.
001 | enter
002 | inside
003 | exit
004 | enter
005 | exit
006 | Traceback (most recent call last):
007 | File "<string>", line 11, in <module>
008 | Exception
hellish
use me instead ๐ณ
๐ 
