#discord-bots
1 messages · Page 980 of 1
@supple thorn Sent it in DMs.
Yeah, if they do not say Ps5 it will raise an error in the console
i dont think i do anymore
bot = commands.Bot(command_prefix = "!")
sold = sold.replace(" ", "+")
r = requests.session()
client = discord.Client()
@client.event
async def on_ready():
print('we are logged in')
@client.bot()
async def ebay(ctx, item):
await ctx.send(f"https://www.ebay.co.uk/sch/i.html?_from=R40&_trksid=p2334524.m570.l1313&_nkw={sold}&_sacat=0&LH_TitleDesc=0&rt=nc&_odkw=elden+ring+ultimate&_osacat=0&LH_Complete=1&LH_Sold=1")
Find great deals on eBay for {sold}. Shop with confidence.
You didn't import commands
Import it from discord.ext
Like ```py
from discord.ext import commands
That is wrong.
In a few places
rip
Ima put this into VSC rq
the sold.replace doesnt work anymore
as i made the code just to work in terminal and had sold as an input
wait dm ive confused myself ngl
You can replace sold as item
Maybe restart the code some
yeah so i wanted to replace "sold" in the url as the item, but had the issue of spaces being inserted into the url and i had to change them to + for the ebay url to work
and now my heads exploded
all the discord bot stuff i followed from youtube, im not even sure what i would change tbh
it dm dont wanna bother you guys too much, do you know where i can find actual educational stuff rather than me just copying from youtube and learning bad code
ive got all the imports above its just my discord token was there so i didnt copy so requests would work
sold i need to figure out how to still convert spaces in the !ebay playstation 5 thing
I fixed some of it, but I cannot define sold for you
so it would be !ebay playstation+5, so that would go into the url instead of a space
yeah thats fine haha ill take a few hours to figure that one out myself😂
I could, but they way you have now is not really working
yeah no worries i will probs remove that
Ask away
how will i convert spaces in the command to +
as i basically want what the user inputs in discord to be put straight into a url
yeah but specifically for sold listings
I made a google search one
Easy
But I would recommand you learn some things first, I did mine with a url button
I am getting ready to go for the night
!e ```py
string = "foo bar"
print(string.replace(" ", "+"))
@pliant gulch :white_check_mark: Your eval job has completed with return code 0.
foo+bar
I probably could i'm here most of the time
I made mine with a url button, took me 2 hours to make it
i think thats what im looking for but im honestly not sure if that would work with swapping out a particular part of a url?
would it?
Depends on the website/API
You'll just need to try and see, there is also other websites that generate URL safe strings but, not sure exactly what you'd do
its just like ebay.com/sold/ps5
and i would want to swap user input for ps5
and if it had spaces in it
i would need them to be converted to a '+'
Try it and see; also make sure Ebay allows you to do whatever you are attemping to do right now
Some services don't allow automated services, so
You're kind of in a grey area, unless otherwise stated in the ToS. negatively or positively
this is just for my personal server they wouldnt be able to figure that out surely
I will help tomorrow 😅. I am tired
Still
if you are trying to do things against ToS of anywhere
we will not help you
oh right nah im actually not haha
its legit for me doing !ebay playstation 5
and getting sent the sold listings
so i can check prices of what theyre selling at
I kinda did this for a button 😅
cant imagine any kind of automation for ebay would be of use tbh, but its more for me to learn coding and do a project that is barely useful
But I would not try using it
oh ah ok
well thank you guys for the help im gonna try figure this out so i can learn a thing or two
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
have a good night
gonna go have a look at this now
Took me 2 months
its 3am here in uk
to understand Python
4am, jesus i been doin it too long
yeah i am completely lost 3 days in but made some useful things for myself and loving it
yeah no problemo, ill be in chat asking stupid questions
Hey guys is there an event or a way to get discord bot to start a task loop when on_ready() fires where I can get a channel context? What I'm trying to do is when the bot starts and logs in and is ready i want it to start a task which throws some message into the channel every X number of seconds...
I got it to work if I explicitly start the task myself with a command but I don't want to issue a command for it to start..
you could use the get_channel method to get the TextChannel object and use the send method on it to send your message rather than fetching the context, you can add a wait_until_ready to make your bot run the task when the bot is ready and you can start the task before you run your bot
@event
async def on_ready(): ...
Bot.channel = Bot.get_channel(channel_id)
@tasks.loop(seconds=10)
async def msg_loop():
await Bot.wait_until_ready()
await Bot.channel.send("uwu")
msg_loop.start()
Bot.run()
hm welcome
won't work....
Bot.channel would always be None
someone here uses discord.py?
almost everyone who chats in this channel
because the clients cache hasnt been populated right
Yessir, get_x methods work only after the cache is ready
I was about to ask where does 'channel_id' come from
what can i say i got it from you😉
you insert your channel_id there
whatever channel you want the bot.channel to bind with
I'm seeing lots of nextcord thing on the chat
I thought so.. how do i procure the channel ID i want to send to? that info can be gotta right out of discord ? or is it by name?
!d discord.ext.commands.Bot.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
well, people here mostly use Disnake or discord.py
A few of them use nextcord and pycord
And the super rare cases like me use hikari
a positional argument only that must be an id/int/snowflake
the super chads using hikari
Indeed
i would change but rewrites!
use hikari, be a chad
😳 you may get some prs from me if you start a hikari rewrite...
i dont do bot dev anymore😔
i do allot of things but i quit bot dev
Relatable, I don't make any public bots anymore
same
just maintaining custom bots for some servers
testing stuff, who cares if I just nuked their server
What are the things
Hello
we are friends
We are?
yes
you have an api ?
no but i can make one, i mostly wrap apis
which have you done so far
Sorry-- if I call get_channel to get the channel object to send to i still need to pass the channel ID as a paramter don't I.. I guess im not understanding how to get that ID
too many to count!
nowadays I'm just looking into hikari source code and trying to sharpen my python skills , Especially oop and decorator concepts
Imma make a custom command handler for hikari later after exams
You can get it here in discord
If you have developer thing turned on
the method returns a channel object yes?
whats the difference between wrapper and actual api?
Presumably, yes
an api is used to communicate between stuff maybe programs or websites and wrappers make commands for each endpoints in a programming language
I see
they are 2 different things,
you send requests to an API , it returns some data or does some stuff
an API wrapper is just a helper type of thing which helps you in making those requests
so like tweepy is a wrapper
you can use APIs without a wrapper too, except for that fact that it sucks
Discord.py is a wrapper
we cant really explain allot because its such a large topic
Anyone know how to format images in md?
parsing!
I was looking at the channel properties.. I don't think i have the developer thing turned on.. the id is an int-- don't see any numbers assoiciated with the channel here in the client
markdown, yeah
Yeah you gotta turn it on to see the options
If you're on mobile you can turn it on in the behavior settings
I think i just switched it on
I don't know about pc though
Ok yeah i see it now... at the bottom of the context menu -- "Copy ID"
you can turn on dev mode from accessibility settings
sarthak
yes oki
wrap the discord api
ill contribute😳
too lazy to learn websockets
bro its not hard
lets just use aiohttps websocket support
I mean
I already made a rest client once
so we dont need to use keepalive to send hbs
😏
Would have to look into aiohttp docs
mhm
got you covered😉
Anyone wanna work on a fairly simple bot with me?
What would itsfunctionality be
Sure
@slate swan
Make a bot which copies okimii
pretty simple, just retrieving stats from an api
too hard to make such a big algo😉
Not really
I see what Api?
make a rest client!
am i really that boring
It's mostly sussy messages
Hypixel
😳 not gonna answer this
what is that
Alright if you're planning to make a GitHub repo or something I may contribute
dont expose me bro
😏
a client for RESTful apis!
Will defitenly make a github for it
Feel free to drop the repository url in my dms
Talking about rest, why does bot.http does not have thisssss https://www.hikari-py.dev/hikari/impl/rest.html#hikari.impl.rest.RESTClientImpl
Could have saved a lot of get_x
Hello I need help 😐
Yeah sure
How to make a muting command
like
i have a muted role
and how to use get so i can get the role with id and add role to member
because dpy bad😔
make a command to where you mention the user as an argument
add role to the person mentioned @meager quartz
ok..
no
Any code reference?
use the timeout endpoint
ok.
!d discord.Member.timeout
await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.10)").
You must have the [`moderate_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") permission to use this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member.edit "discord.Member.edit").
hmm ok
Any code for it using discord.py anyone can give me 🙂 😄
docs!
ok
i dont think discord.py has timeout
it does, but you need to use the master branch
4 messages above lmfao
never doubt what oki says
You can also use Member.edit
they doubt me because no helper role😔
why would you
sorry i have a mental disorder where i forget stuff, sorry i am mentally stupid
Because that's the same endpoint that member.timeout uses
i dont blame you
ik. but why use edit when you already have a whole coroutine!
Cz timeout also calls the edit method in the backend
Cause you can perform other operations at the same time, like Changing the members name to "this dumbo was spamming" with the same.method
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/member.py at master · Pycord-Development/pycord
you sound like you made this
discord/member.py line 957
await self.edit(timed_out_until=timed_out_until, reason=reason)```
shhhhhh
i know🙄
i wonder why the method doesnt return a member object?
it returns None
bro thats my point
why would it
because you just timed out a member🗿
it would be a bit handy tho
well, they could have just ```py
return await self.edit(timed_out_until=timed_out_until, reason=reason)
yeah
since the edit method returns Member | None it would return same
because if you're calling a method on a member object you already have the member?
therefore the member obj will be updated
Its working-- thank you very much!
yes but in some situations it could be used
in which cases i dont know of
sometimes its better for them to return the member object, especially for people who use chaining
vaskel does have a point of updating the object yes but it would be a bit useful to return the updated member object no?
You're welcome if you need any more help hit my dm i'm usually here for 12 hours everyday so a good chance you won't see me offline
it reminds me of the method iirc it was pop or something like that a method of the list object which doesnt return a updated list but it returns None
i mean, whats the point of returning it in the .edit method and not in .timeout
you just need to a single return
Yup, pop and get for dict
yeah
!d dict.pop
pop(key[, default])```
If *key* is in the dictionary, remove it and return its value, else return *default*. If *default* is not given and *key* is not in the dictionary, a [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError "KeyError") is raised.
!d dict.get
get(key[, default])```
Return the value for *key* if *key* is in the dictionary, else *default*. If *default* is not given, it defaults to `None`, so that this method never raises a [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError "KeyError").
it just updates them and doesnt return the updated ver
There was another method, which returns None but also removes the value
ofc it would return None youre deleting the list.
does cog_check apply to slash?
Nope
maybe it would for d.py since it has "hybrid" commands but I'm not too sure
dict(member.guild_permissions)
this is implemented?
disnake/flags.py lines 144 to 150
def __iter__(self) -> Iterator[Tuple[str, bool]]:
for name, value in self.__class__.__dict__.items():
if isinstance(value, alias_flag_value):
continue
if isinstance(value, flag_value):
yield (name, self._has_flag(value.flag))```

How can I dump more than 1 thing in a json file
e.g {channel_name: test, test, test channel_id: 24334788888, 757455545556566, 867767565565
you could create a nested dict
heyo eito
ayo helo ashley :>
{
"12234566": {
"channel_name": "uwu",
"channel_id: "9966546777"
}
}
uwu
yes you
smh
That’s not dumping more than 1 thing
You gotta append to the dict everytime
with open(file) as f:
data = json.load(f)
data[str(guild_id)] = {}
data[(str(guild_id)]["key_1"] = "value_1"
with open(file, 'w') as f:
json.dump(data, f)```
you can create keys like this
user cant see the channel when they create a new channel
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
client.load_extension(f"cogs.{filename[:-3]}")```
How to convert this code to dpy 2.0
Error?
no
💀 it is not related to discord.py
it should work for all lmao
see your spelling
How should I define client
spelling
Bruh
in argument it is cleint and there your'e using client
Ty
there is no error, when they creates a channel it dont show up to them
permission issue probably
Change {member.mention} to {user.mention}
import discord
from discord.ext import commands
class help(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
async def help(self, ctx):
help = discord.Embed(color=discord.Color.orange())
help.set_author(name="Warrior bot help", icong_url="")
help.add_field(name='`help`', value='This command took you here!', inline=False)
help.add_field(name='`giveaway`',
value='Can only be accessed by users with administrator permissions.\nStarts a giveaway for the server! This command will ask the host 3 questions. The host will have 30 seconds per question to answer or they will be timed out!',
inline=False)
help.add_field(name='`reroll #channel_name message id`',
value='Can only be accessed by users with administrator permissions.\nThey must follow the command with the copied message id from the giveaway.',
inline=False)
help.add_field(name='`ticket`',
value='Can only be accessed by users with administrator permissions.\nWe will figure that out later',
inline=False)
help.add_field(name='`kick`',
value='Can only be accessed by users with administrator permissions.\nWe will figure that out later',
inline=False)
help.add_field(name='`ban`',
value='Can only be accessed by users with administrator permissions.\nWe will figure that out later',
inline=False)
help.set_footer(text='Use the prefix "!" before all commands!')
await ctx.send(embed=help)
def setup(client):
client.add_cog(help(client))```
Is there something wrong with this command
There are no errors
But command help doesn't work
Ooh
in your main.py file.. do ```py
bot.remove_command('help')
nope
I alr have it in my main file
🤔
Ands it's better to subclass the Help command , quite easy task
in discord.Embed,, try adding title and description
Title and description doesn't matter
show the errors
Change it back to member
ok
no,, i added custom help in bot.py folder/main folder
i am not sure about that
Oh this is cogs
Yes
extension prob
r u using some custom class? 🤔
I don’t use cogs
Yes
yeah
oh
it's a coroutine in 2.0
anyone knows that?
but load_extension isn't a coroutine :'/ i'm using 2.0
it is
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client"), This class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") and is automatically set upon instantiating the class.
error never lies
!d discord.ext.commands.Bot.load_extension
await load_extension(name, *, package=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Loads an extension.
An extension is a python module that contains commands, cogs, or listeners.
An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.
Changed in version 2.0: This method is now a [coroutine](https://docs.python.org/3/glossary.html#term-coroutine "(in Python v3.10)").
🤔

wait.. which lib it is?
Is it bc I am using dpy 2.0
@sullen pewter
Wdym
it means you have to await load_extension
Idk coroutine 2.0
This error is raising since I'm using a task while closing the bot
Traceback (most recent call last):
File "/data/data/com.termux/files/home/codes/otaku/venv/lib/python3.10/site-packages/discord/ext/tasks/__init__.py", line 266, in _loop
raise exc
File "/data/data/com.termux/files/home/codes/otaku/venv/lib/python3.10/site-packages/discord/ext/tasks/__init__.py", line 241, in _loop
await self.coro(*args, **kwargs)
File "/data/data/com.termux/files/home/codes/otaku/extensions/chat_ping.py", line 11, in chat_revive
general = await self.bot.fetch_channel(config.general_chat)
File "/data/data/com.termux/files/home/codes/otaku/venv/lib/python3.10/site-packages/discord/client.py", line 1688, in fetch_channel
data = await self.http.get_channel(channel_id)
File "/data/data/com.termux/files/home/codes/otaku/venv/lib/python3.10/site-packages/discord/http.py", line 439, in request
async with self.__session.request(method, url, **kwargs) as response:
File "/data/data/com.termux/files/home/codes/otaku/venv/lib/python3.10/site-packages/aiohttp/client.py", line 1138, in __aenter__
self._resp = await self._coro
File "/data/data/com.termux/files/home/codes/otaku/venv/lib/python3.10/site-packages/aiohttp/client.py", line 399, in _request
raise RuntimeError("Session is closed")
RuntimeError: Session is closed
I did
you didn't
In the cog file or in the main file
where you load your cogs
@client.command
async def load(ctx, extension):
client.load_extension(f"cogs.{extension}")
await ctx.send("Loaded {extension}")
@client.command
async def unload(ctx, extension):
client.unload_extension(f"cogs.{extension}")
await ctx.send("Unloaded {extension}")```
It's this thing
I am loading them
yes.. await load_extension/reload_extension
yes
Oh ok
@client.command()
Help
show the task
class ChatPing(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.chat_revive.start()
@tasks.loop()
async def chat_revive(self):
general = await self.bot.fetch_channel(config.general_chat)
try:
await self.bot.wait_for('message', timeout=config.ping_timer, check=lambda x: x.channel.id==general.id)
except:
await general.send('<@&964751954104422451> time do you stuff!')
hm
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
client.load_extension(f"cogs.{filename[:-3]}")```
what should I do here
await load_extension
Ok
But await only works in async function
+^1 :")
Use it in a function called setup_hook
How
Subclass commands.Bot
In cogs file
And add a method inside it named setup_hook
How?
Ok
You're probably making to many request at a time, until it crashes and closes the session. You need to set the loop with a specific interval.
Ok
:")
Lol
class MyBot(commands.Bot):
def __init__(self):
intent = discord.Intents.default()
intent.message_content = True
super().__init__(command_prefix=commands.when_mentioned, intents=intent)
async def on_ready(self):
print(f"Logged in as {bot.user}(ID: {bot.user.id})")
async def setup_hook(self):
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
await client.load_extension(f"cogs.{filename[:-3]}")
client = MyBot()
Oh wait, I missed something, it only happens while closing the bot. You can use on_disconnect event to check whether it is disconnecting, and cancel the task there using task.cancel(). Then, you can start it again in on_connect event.
Ok lemme try
If I have intents in my main file do I need to write it in my cogs file?
No
Ok
I have to delete this fin my main file
Cuz there's is already in cog
@client.event
async def on_message(message):
if message.author.id == client.user.id:
return
msg_content = message.content.lower()
if message.author.guild_permissions.administrator:
return
if message.author.bot:
return
links = ['http', 'discord.gg']
with open('antilink.json', 'r') as f:
key = json.load(f)
if f'{message.guild.id}' not in key:
pass
else:
if any(word in message.content for word in links):
await message.delete()
await message.channel.send(f"{message.author.mention} No Links/discord invites allowed in this channel.")
await client.process_commands(message)
My commands aren’t working
Use this @sullen pewter
Any errors?
No but I did put await client.process_commands(message)
And idk why it’s not working
Hmm lemme try
they don't need to
They should
do this ```py
async def func():
# load cogs here
client.setup_hook = func
Anyone know how I can make a whitelisting system using json
For this
Why json
Because I’m not using db yet
Suffer the consequences
Like this?
async def setup(bot):
@tasks.loop()
async def chat_revive():
general = await bot.fetch_channel(config.general_chat)
try:
await bot.wait_for('message', timeout=config.ping_timer, check=lambda x: x.channel.id==general.id)
except:
await general.send('<@&964751954104422451> time do you stuff!')
@bot.event
async def on_connect():
await chat_revive.start()
async def on_disconnect():
await chat_revive.cancel()
avoid bad practices for the moment
That isn't related to discord bots
scrapping
ew what is that?
and idk if that would work, since you are nesting tasks and events in one function
good to see
If u think that's ew, then don't look at this: https://github.com/DevDungeon/Cathy/blob/master/cathy/__init__.py#L98-L151
Okay so, I've tested something and you actually do not stuff like on_disconnect, you simply need to do task.add_exception_type(RuntimeError) and it should be good.
In the init method?
Anywhere you like, but make sure that function got executed before your program ended.
is discord embed color use hex?
How can I use a variable for my color
Now it says
Task was destroyed but it is pending! task: <Task pending name='Task-4' coro=<Loop._loop() running at /data/data/com.termux/files/home/codes/otaku/venv/lib/python3.10/site-packages/discord/ext/tasks/__init__.py:247> wait_for=<Future pending cb=[Task.task_wakeup()]> cb=[gather.<locals>._done_callback() at /data/data/com.termux/files/usr/lib/python3.10/asyncio/tasks.py:720]>
Hello?
Can you show your code? I can't actually reproduce this.
Here
class ChatPing(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.chat_revive.start()
self.chat_revive.add_exception_type(RuntimeError)
def cog_unload(self):
self.chat_revive.cancel()
@tasks.loop()
async def chat_revive(self):
general = await self.bot.fetch_channel(config.general_chat)
try:
await self.bot.wait_for('message', timeout=config.ping_timer, check=lambda x: x.channel.id==general.id)
except:
pass
# await general.send('<@&964751954104422451> time do you stuff!')
async def setup(bot):
await bot.add_cog(ChatPing(bot))
I still can't reproduce the problem, it worked fine in my end.
Here's a screenshot
First of all it turns after using Ctrl+C twice
Okay so this is quite unexpected but for the last time could you try something like this? And why do you want to suppress these kinds of errors though?
.
.
beautiful
hi
Eh, there is too much useless code in there ngl
half of it doesnt even make sense but lets not talk about that, ill go bleach my eyes
Well, it isn't really maintained anymore. Still uses dpy v1.7 haha
I have a PR opened but the owner doesn't have time to review and merge it, moreover as long as it runs, no one gives a fuck
righty
for ch in []:
text.replace```
😔
a for loop every message so uwu
Lol
Hey folks-- with the async keyword.. how does this actually work.. is it like a fork almost where the main loop continues to run splitting time with whatever the async function is doing-- thereby giving a discord bot for example the ability to process multiple requests simultaneously.. am I understanding this correctly?
Man you love hyphens
How to send a lot of text by using one command
wha
@client.command()
async def hi(ctx):
await ctx.send("")
Then
then do a multiline string
Ok
and send(chat_rules)
does it not send?
It doesn't
My bot doesn't respond to any commands
I don't think the problem is in the text
u using the right prefix?
how to connect asyncpg
It worked
what was the problem?
use create_pool method
and connect it with correct credentials :'/
error is coming
show the error
How can I make the bot respond without sending channel and message id?
@client.command()
@commands.has_permissions(administrator=True)
async def reroll(ctx, channel: discord.TextChannel, id_: int):
# Reroll command requires the user to have a "Giveaway Host" role to function properly
try:
new_message = await channel.fetch_message(id_)
except:
await ctx.send("Incorrect id.")
return
# Picks a new winner
users = [user for reactions in new_message.reactions
async for user in reactions.users()
if user != client.user]
winner = random.choice(users)
# Announces the new winner to the server
reroll_announcement = discord.Embed(color=discord.Color.orange())
reroll_announcement.set_author(name=f'The giveaway was re-rolled by the host!',
icon_url='https://i.imgur.com/DDric14.png')
reroll_announcement.add_field(name=f'🥳 New Winner:', value=f'{winner.mention}', inline=False)
await channel.send(embed=reroll_announcement)
@giveaway.error
async def giveaway_error(ctx, error):
if isinstance(error, commands.BadArgument):
embed = discord.Embed(title=f"Failed.", description=f"Your time contained letters.", colour = discord.Colour.red())
await ctx.send(embed=embed)```
OSError: Multiple exceptions: [Errno 111] Connect call failed ('::1', 5432, 0, 0), [Errno 111] Connect call failed ('127.0.0.1', 5432)```
u sure that port number is correct?
also
send whole traceback along with code so that i can look into it :'/
i didnt entered port number
async def create_db_pool():
bot.db = await asyncpg.create_pool(database="catchydb",user="postgres",password="golugolu")
bot.loop.run_until_complete(create_db_pool())```
this is my code
Pretty much, if u want to learn more about asynchronous programming in python, check the pinned messages in #async-and-concurrency
you've to pass port too
how? where will i get the port number
in 2nd line ```py
bot.db = await asyncpg.create_pool(database="catchydb",user="postgres",password="golugolu", port = "6969", host = "127.0.0.1")
i have to use this port number
where 6969 is just an example
i dont know where it shows
like do u have it installed? on your pc? postgresql
yes
how do i check my port
google says that default port number is 5432 for postgresql@granite parcel if u haven't changed it
i havent changed lemmie check
added host will be same ?
yeah.. like 127.0.0.1 is same as localhost
and since its installed in your pc.. so that should be it
Can someone help me
raise OSError(err, f'Connect call failed {address}')
ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 5432)```
show me traceback
and btw do u have your postgresql open? if not, then try to run file again after opening it
opened
🤔 try to do again
maybe try 'localhost' for host
🤔 could be
again same error?
yes
no
then do it & try again
ok
:'/
in _get_new_connection
con = await connection.connect(
TypeError: connect() got an unexpected keyword argument 'localhost'
container@pterodactyl~ Server marked as offline...```
oh
@granite parcel are you sure the postgresql server is actually running?
yes
it showed server connected
yes
installed on your pc
thank you :")
my intention wasnt to correct prepositions but anyways
lmao
that's all okay lmao
i can help
Ooh ty
beside
lmao behind
idk
installed under your pc
about hardware and stuff
💀 bro, u doctor strange or wot?
LMAO 😂
:>
helo ryuga :>
you need the bot to save it when you first run the command, the one that makes the rolling thing or whatever
so like, when you do /giveaway or idk get both channel id and message id
Ty, but I alr resolved the problem
oh good
title=f"",
description=f"",
set_thumbnail="./tmgmidvitelogonowords.png",
colour=0xffffff
)
await ctx.send(embed=embed)``` how do I set the thumbnail? this isn't working
In embed.url: Scheme "./tmgmidvitelogonowords.png" is not supported. Scheme must be one of ('http', 'https').```
alr
@client.command()
@commands.has_permissions(administrator=True)
async def giveaway(ctx):
# Giveaway command requires the user to have permissions to function properly
# Stores the questions that the bot will ask the user to answer in the channel that the command was made
# Stores the answers for those questions in a different list
giveaway_questions = ['Which channel will I host the giveaway in?', 'What is the prize?',
'How long should the giveaway run for (in seconds)?', ]
giveaway_answers = []
# Checking to be sure the author is the one who answered and in which channel
def check(m):
return m.author == ctx.author and m.channel == ctx.channel
# Askes the questions from the giveaway_questions list 1 by 1
# Times out if the host doesn't answer within 30 seconds
for question in giveaway_questions:
await ctx.send(question)
try:
message = await client.wait_for('message', timeout=30.0, check=check)
except asyncio.TimeoutError:
await ctx.send(
'You didn\'t answer in time. Please try again and be sure to send your answer within 30 seconds of the question.')
return
else:
giveaway_answers.append(message.content)
# Grabbing the channel id from the giveaway_questions list and formatting is properly
# Displays an exception message if the host fails to mention the channel correctly
try:
c_id = int(giveaway_answers[0][2:-1])
except:
await ctx.send(f'You failed to mention the channel correctly. Please do it like this: {ctx.channel.mention}')
return
# Storing the variables needed to run the rest of the commands
channel = client.get_channel(c_id)
prize = str(giveaway_answers[1])
time = int(giveaway_answers[2])
# Sends a message to let the host know that the giveaway was started properly```
give = discord.Embed(color=discord.Color.orange())
give.set_author(name=f'Giveaway!', icon_url='https://i.imgur.com/VaX0pfM.png')
give.add_field(name=f'Prize: {prize}!',
value=f'React with 🎉 to enter!\n Ends in {round(time / 60, 2)} minutes!', inline=False)
end = datetime.datetime.utcnow() + datetime.timedelta(seconds=time)
give.set_footer(text=f'Giveaway ends at {end} UTC!')
my_message = await channel.send(embed=give)
# Reacts to the message
await my_message.add_reaction("🎉")
await asyncio.sleep(time)
new_message = await channel.fetch_message(my_message.id)
# Picks a winner
users = [user for reactions in new_message.reactions
async for user in reactions.users()
if user != client.user]
winner = random.choice(users)
print(users)
How can I make it so time is not only in second
So instead of second I could type 1m or 1 day
There is this btw 4 real https://developer.4d.com/docs/en/Concepts/about.html
hey can anyone help me with this:
I want to store a user's information like giving them a wallet and then adding some money to it every time they use a certain command. I want to store all of this in the replit database, is there a way to do it?
Guys is there an event where when a member joins a voice channel
yes
okay
so, how do I add a databse in replit db for the user?
and add some value to that database when needed
from replit import db
replit's db is just a JSON file, just index it and asign a value to a key
Is the mathjspy package reliable for implementing a calculator function in a discord bot?
sure
maybe your bot doesn't have member intents
@boreal ravinein what sense?
any errors?
@boreal ravinethat's the problem, even there are no errors
await bot.process_commands(message)
maybe you need to add this line here, just replace the word commands with events ??
hi guys do you know how a bot can delete a specific message when a user reacts to the emoji that the bot added ?
@pure sparrow await message.delete()
oh cool many thanks. and we must get the message id for that ?
no
how to make DISCORD.PY read the code from one code file and passed it to another, namely to separate event and commands ??
that is, divide the decorators into two files and transfer them to the third
Definitely not
Hey coke
that's the problem, even there are no errors
Hello, I have a discord bot which has a voting system where users vote 👍 or 👎 how can I make it so the users can react 👍 or 👎 to other messages without the vote counting for the vote?
@slate swan it's unlikely that they will help you here in the next few hours, so it's better to duplicate your message in a couple of hours.
What do you mean?
Hello, I have a discord bot which has a voting system where users vote 👍 or 👎 how can I make it so the users can react 👍 or 👎 to other messages without the vote counting for the vote?
I don't know what needs explaining. Elaborate.
I don’t need to see it again.
How was I suppose to know that.
You want the users to react with the reactions
Yes.
@frozen patio help!!!
You need intents.
Then make an event where the bot adds them
And then the users can react
No shit sherlock.
Then what do you need help with?
Yeah
(I can't react but pretend theres 2 reacts on this message 👎 and 👍 )
@slate swan I have been writing the same question for several days in a row and everyone is silent or ignoring...
Do an on_message event
I've answered the question.
You need intents.
And do what in it?
Yeah, the bot can do it with a simple on_message event
I am on my phone so I cannot write the script for you
But I can explain it
You are not elaborating.
I will try to
I told you what you need to do
You did not tell me.
Make an event when someone sends a message it adds the reactions
An on_message isn't required for that.
An on_raw_reaction_add is.
on_raw_reaction_add Will cast a vote to any message that has a thumbs up or down emoji added
Yea, I thought it needed an on_message event
Yea but you want it to be automatic no?
@client.event
async def on_raw_reaction_add(payload):
if (payload.member.id == 9625895xx07190xx02):
return
if (payload.emoji.name == "👎"):
// add the vote.
elif (payload.emoji.name == "👍"):
// add the vote.
else:
pass
If I react thumbs up or down to any message but the poll, it will add the vote, how can I prevent this.
Why are you doing a member Id
That's the bot ID.
Mmm
@brave forge Add the intents.
Maybe set it to a specific channel 🤔
Right... But that channel will be removed and added multiple times.
It's like a private vote for a select members.
Sorry I didn't clarify that!!!
Well anyone who can see a channel can react if there is already reactions.
I do not understand what you have just said sorry.
I retyped it
Got it.
👍
I still don't understand what you meant.
Anyone who can see this specific channel of yours can click your the reactions of they are there.
Hold on, I've just thought of something, can I somehow get the contents of the reacted message and check if it contains words like "New Poll" etc?
How can I get the content of a reacted message via on_raw_reaction_add?
Yeah
<@&831776746206265384>

!mute 419481276765175808 Take a break and think about if you really want to be here.
:incoming_envelope: :ok_hand: applied mute to @brave forge until <t:1650116240:f> (59 minutes and 59 seconds).
You could use a filter for that ig
Thank you.
Yep, thats what I was thinking.
Like a message scan filter thing.
Yea I use it in my server
When someone cussed it deletes it and sends a warning message.
You could also check the message id
That's different.
Match it with what?
Set the message id in a database with the message you sent
Ahh that's given me an idea! I forgot but earlier I had saved the vote message id.
Yep, smart.
I was gonna say it earlier
Yea coke better at python than me
I was actually typing it but docs were slow af
And i wanted to be right
Ok.
Anytime pal 😉
I was actually gonna suggest both your thing and my thing

You're welcome
Dm me it
Really? :OOO
Curios on what you were gonna say
uh sure
Actually your thing was my first idea
But i saw you suggested it
So i had to think of a better one
Yea 😂
Why are docs slow for me
Hi
😔
Got to 1 up me
say hello to yt
nah it wont make much sense now
Say it
Mk
yes ashley what are you afraid of, JUST SAY IT!!!!!!!!!!!
Xd sparky
Lmao
I got scared after reading your message no shit
I don't think the mods would like that
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
fr, gonna tag it as discouraging and rude
I did for a reason like 10 minutes ago
Hunter pops
It's a topic channel
did you mean that or that
We can discuss and help
Topic chat/help

Thank you hunter
No pun intended
Helpful person
if none of this is on-topic for this channel, go to the off topic channels.
this channel is not made for regular discussion but instead help with discord.py and it's forks.
.topic
Suggest more topics here!
Time to procastinate me making the duck wrapper for a duck api
right
I'm out also hello kayya
is there somewhere i can learn how to make a discord bot from scratch
ive check online and theyre either missing imports or diff discord packages etc
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
Hey hazbob!
hey man did you have a good night
Bro i was struggling with vcokltfre's name
No
😂
Same
guys after staying in cyro-pod for 1 year i get to know discord py devs finally decided to update their lib, can some1 give me link for the latest docs
!d docs
Documentation#
• Documentation style contains everything you need to know about writing docstrings, which are rendered to produce HTML documentation using Sphinx
• Rendering Documentation with Sphinx it’s important to check how changes to the documentation render before merging a PR; this document explains how you can do that
@slate swan I'm just tired of writing the same question already. And when I answered a little rudely I got a mute
what's your question man, tell me
Then don't be a little rude then
these people are jealous of you, don't worry just tell me, @edgy wave
No I just can’t read what he says
what he says?
@slate swan this
Cogs buddy
Kayya is first
xD
Вы можете сделать это легко, используя функцию "cogs", и, черт возьми, эти люди не говорят здесь по-русски, поэтому, пожалуйста, постарайтесь вести разговор только на английском языке.
I think its network issue cuz I'm not in my home rn
he won't speak russian now
Imagine Russian reply*
@edgy wave мы сейчас в порядке?
@slate swanthank you very much)
Nice
Yeah I can’t understand Russian xD
Google translate exists
@edgy wave let me know if you need help with anything
I hate that loop
🔄
What
settings
I banned him from my server for disrespecting members
Mmmm I need to do that
That language python dude
c'mon guys he could be new, let's just forget about it
Yeah what’s done is done
There is no promotion LMAO
a bot that can control my pc
it's very useful for me when i have to control my pc using my phone
I finally learned how to make my bot send a DM when someone is kicked/banned
None ;")

Oh cool, though that works only if the bot has atleast 1 mutual server with the bot
it's simple, just run the send-message function before the ban

Yea I learned that 😶

Im proud to send the msg hello world
The bot is in my server where I ban, so it sends it then bans
..
Suggest more topics here!
🐢I focus on making my bot bases first
all the classes, dataclasses, database etc
by that time i forget that I'm making a discord bot
,say thanks u XD
A mute system where it gives you a timeout
..
Cannot seem to figure that out yet
ctx.send()
! discord.Member.timeout you can do it with discord.py master :D
the pain we 'russians are in' is f*cking up my brain day-by-day
how can I make tempmute? py @commands.command() @commands.has_permissions(manage_messages=True) async def tempmute(self, ctx, user: discord.Member, *, duration="", reason="Reason unspecified"): embed = discord.Embed( title=f"Mute: {user.name}", duration=f"Duration: {duration}", description=f"Reason: {reason}\nBy: {ctx.author.mention}") await ctx.message.delete() mutedRole = discord.utils.get(ctx.guild.roles, name="Muted") await user.add_roles(mutedRole) await ctx.channel.send(embed=embed)
!d discord.Member.timeout
await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.10)").
You must have the [`moderate_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") permission to use this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member.edit "discord.Member.edit").
Yea 🤔
How do I make a custom rich presence status for my bot?
good idea actually
Well, discord allows you to change the playing, listening etc for a bot
But you can't have a rich presence
I mean the listening
!d discord.ActivityType.listening
A “Listening” activity type.
Thanks
Use this as type in discord.Activity
google translate someone messes with languages, you should maybe try there if it's not currently drunk
.topic
Suggest more topics here!

just try to speak English at your best level, you don't need it to be perfectly correct
!rule 4
4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.
Tho
Ohok
my family travels the world, and most of us know english, i wanna go back home to russia(stuck in sydney) but as you know the crysis is hitting, ru & ukraine, i hope the war end soon
btw guys
do you use github copilot while coding?
It actually works now, thanks a lot 😄
it's not about being "lazy" it helps you code, by suggesting you, and it's up to you if you wanna use it's code or stick with yours, but overall it has helped me a lot
Yeah I just do not like it
I need you to get faster at typing too
nah, I find that annoying and never helpful for me
tabnine for me
it helped me a lot with commands & features but honestly i never felt lazy or anything it suggests me what i know, and it's really good if you wanna just save your time
tabnine uses a lot of my memory
Hi, what does the discord userid have to do with the creation date again?
same but its all I need ig
nothing
It does
you should give github copilot a try, you know trying something isn't bad, just give it a shot
I'm pretty sure I heard something like this on this server
But the id is way too big for a timestamp
oh nvm, I took it the wrong way
thanks 💙
discord epoch xD
I would explain it to you further but idk
I think the picture explains it pretty well
Wasn't it something like this
All I know is you have to use the bitshift operator to get the date an account was created from their id
do u use vscode?
Created at works
And you bitshift right 22
Then add discord epoch
Oops
dw bro just cz u use gh copilot doesn't mean u can't code lol
i too setted it up never coded sine then :)
def id_to_datetime(id: int):
return datetime.datetime.fromtimestamp((id >> 22) + 1420070400000)```
are bitwise operators really useful?
!e ```py
from datetime import datetime
timestamp = ((381799048228896788 >> 22) + 1420070400000) / 1000
print(datetime.fromtimestamp(timestamp))
@supple thorn :white_check_mark: Your eval job has completed with return code 0.
2017-11-19 13:33:06.581000
Sometimes
Yeah this thing
But not often
for wut?
Sure are
i can't think of a scenario of me using them
Bitwise operators are the best
They’re faster than doing regular arithmetic
Computers are incredibly good at flipping bits
mostly
Don't you also need to divide by 1000 since it's in ms
how'd u take advantage of thier fast nature?
Or am i just stupid
Instead of doing regular arithmetic like adding; subtracting you can use bitwise to do them instead
@sweet pilot man i can't understand what you just said here
u could use intellisese ryt?
if you use python extension with vscode intellisense is already a part of it
Do not worry my brethren, just because you use GithubCopilot doesn't mean you cannot program laughing out loud

yeah I do
just because you use (not cannot) lol
I recently used bitwise operator: was making a bot for my dashboard, and only want to show guilds where the user had “manage server” permission in, so I requested all guilds from the proper endpoint. The permissions are given as an integer though, so I had to use bitwise and to see if the user has the right permissions from that integer
I got copilot and still keep it off 🗿
thanks i finally understood
oh u meant u don't understand the word simplifications 😂
sry bro just forced of habit
@sweet pilot i gave my personal opinion to someone who thought it makes them lazy, not suggesting just telling them, it helps me code faster
I was thinking of the "doesn't mean you cannoy program" when i was writing that part and used cannot
ohhhh
gotchcha
r u able to show any code?
to better understand the usecase
'Command' object has no attribute 'strip'
why do I get that when running
Yeah sure, I’m not on my computer but I’ll look
the command object doesnt have that attr only strs
It gave me that on bot.run(token) tho lol