Discord Rich presence - python

So basically I'm trying to have my account on discord online 24/7 so I wrote a bit code for that in python, now I want to add a rich presence, with a timer (how much time elapsed since I started the game) a game title, a large image key and all of that stuff and I have no idea how to write it, anyone knows how to help?
My code so far in main.py...
from discord.ext import tasks, commands
client = commands.Bot(
command_prefix=':',
self_bot=True
)
game = discord.Game("Game Title")
#client.event
async def on_connect():
await client.change_presence(status=discord.Status.online, activity=game)
keep_alive.keep_alive()
client.run(os.getenv("TOKEN"), bot=False)```

Using self bots is actually against the terms of service. Instead of using discord.py use pypresense You can do a lot more with it.
This is an example of time elapsed
from pypresence import Presence
import time
"""
You need to upload your image(s) here:
https://discordapp.com/developers/applications/<APP ID>/rich-presence/assets
"""
client_id = "client_id" # Enter your Application ID here.
RPC = Presence(client_id=client_id)
RPC.connect()
# Make sure you are using the same name that you used when uploading the image
start_time=time.time() # Using the time that we imported at the start. start_time equals time.
RPC.update(large_image="LARGE_IMAGE_HERE", large_text="Programming B)",
small_image="SMALL_IMAGE_HERE", small_text="Hello!", start=start_time) # We want to apply start time when you run the presence.
while 1:
time.sleep(15) #Can only update presence every 15 seconds
You can install it using pip install pypresence

I know this is an old question, and I am sorry if this is not what you are looking for, but discord.py is not made for user-bots (atleast not intended), I recommend using something like lewdneko's pypresence. It has bizzare compatibility/detection (Linux, especially Arch) issues but when it works, it works very well actually. It also has an attribute for time_elapsed, which you can use with something like time.time(). (afaik)

Related

Is it possible to make the cooldown time only last while a command is running in discord.py?

I'm developing a discord bot, and one of it's features is a command that feeds memes, it's only available for some channels I'm the server, and I wanted to know if it's possible to put the command in cooldown while it's being used, then a new feed couldn't be started while there's already one feed being executed, also I wanted this to only happen at a channel, for example: A user used the feed command in channel-1, of him or someone try to start a new feed before the current one ends it will fail, but if another feed is started at channel-2 it should work.
I don't know if it's possible, but if yes, how should it be done? I'm currently using #commands.cooldown decorator to put a normal cooldown on the command.
So I think the way to do it is without using the #commands.cooldown decorator and some custom way of doing the cooldown.
# use datetime
import datetime
# define this somewhere
meme_feed_cooldowns = {}
.
.
.
#client.command(description="feed memes")
async def meme_feed(ctx):
now = datetime.datetime.now()
channel_id = ctx.channel.id
previous_time_triggered = meme_feed_cooldowns.get(channel_id, None)
if previous_time_triggered:
# check if we're in cooldown
time_since_triggered = now - previous_time_triggered
if time_since_triggered.total_seconds() < 1800:
# it's not been 30 minutes since last triggered
# send some kind of message to inform the user and then return
return
# set the cooldown time to the current time
meme_feed_cooldowns[channel_id] = now
# do whatever you want to do
Something kind of like this. There's other improvements you could make - make the "cooldown dict" more complicated and also have whether or not the command is ongoing. Hopefully gives you enough ideas to get you going!

Discord bot, current date as status

i have looked a bit and tried multiple things and im stumped. Im going to be hosting a discord bot 24/7 and i want the Status to display the current date and time, as example. 11/30/22, 10:51 PM, in eastern time. Thanks!
tried methods such as "
activity=discord.Game(datetime.datetime.utcnow().strftime("%H:%M")),"
You can use tasks.loop, creating a task that updates every minute and changes the bot's Status to the current time.
tasks.loop is a decorator which executes the decorated function repeatedly at a defined interval. Then you just need to spawn the loop in an asynchronous context, of which I personally use setup_hook in this example.
from discord.ext import tasks
import datetime
#tasks.loop(minutes=1):
async def set_status(): # name is unimportant, but it must not take arguments
name = datetime.datetime.utcnow().strftime("%H:%M")
activity = discord.Game(name=name)
await client.change_presence(activity=activity)
#client.event
async def setup_hook(): # name is important, and it must not take arguments
set_status.start()
Replacing client with the name of your client as appropriate (usually client or bot).

Discord.py Bot send messages at certain times

I host a discord.py bot on a server for me and some friends, and have been trying to get a certain 'feature', where the bot will send a message every day, twice daily, once in the morning, once in the night, just saying general "good morning" and "good night!" I have spent hours looking through other peoples codes, and similar questions, and this is the best I can find/have gotten (It's taken from another user's 'python alarm', and I tried to hook it up to the bot.
from datetime import datetime
from threading import Timer
x = datetime.today()
y = x.replace(hour=21, minute=45, second=40, microsecond=0)
delta_t = y - x
secs = delta_t.seconds + 1
channel = client.get_channel(806702411808768023)
async def Goodnight():
await channel.send("Good night! Make sure to go to sleep early, and get enough sleep!")
print("Night Working")
t = Timer(secs, Goodnight)
t.start()
I keep getting the same error(s), usually about the message not being async or await-'able' (?). I am fairly new to coding/python, sorry if anything is obvious. I really do not know what to do, and I have found some promising solutions, though those make the whole bot the alarm, and force it to 'sleep' while waiting, while I want mine to still function normally (run other commands), if possible? Any help appreciated
This can be done using the tasks extension:
import datetime
import discord
from discord.ext import tasks
client = discord.Client()
goodNightTime = datetime.time(hour=21, minute=45, second=40) #Create the time on which the task should always run
#tasks.loop(time=goodNightTime) #Create the task
async def Goodnight():
channel = client.get_channel(806702411808768023)
await channel.send("Good night! Make sure to go to sleep early, and get enough sleep!")
print("Night Working")
#client.event
async def on_ready():
if not Goodnight.is_running():
Goodnight.start() #If the task is not already running, start it.
print("Good night task started")
client.run(TOKEN)
Note that for that to work you need to have the latest version of either discord.py or a fork which supports version 2.0. If you don't have it yet, you can install it via
pip install -U git+https://github.com/Rapptz/discord.py

How do I use Tkinter and Telebot together?

I've been working on a Python project where I'm stuck at one point. Basically, I have a GUI that updates automatically once 5 seconds. I have done it using the method .after(5000, main) where main function looks like the following.
def main():
global lastthreshold
global run
global lastaction
global bakiye
global lif
global gsecenek
paributl, binancedolar, paribudolar, dolar = getData()
farklow, farkhigh = diff(paributl, binancedolar, paribudolar)
data = guiDataMaker(paributl, binancedolar, paribudolar, farklow, farkhigh)
gui = Gui(data, dolar, lastthreshold, alsatmiktar, bakiye)
#print(*data, sep="\n")
#print(*cooldown.items(), sep="\n")
if run:
lif = gui.gui()
for i in paributl.keys():
cooldown[i] = "NONE"
run = False
gui.secenek.set(gsecenek)
runbot = runBot(lastthreshold, bakiye, data, cooldown, alsatmiktar)
if runbot[0] != None:
currency, guncelfark, fiyat, newbakiye, buydate, islem = runbot
bakiye = newbakiye
guncelislem = (currency, guncelfark, fiyat, newbakiye, buydate, islem)
lastaction = (currency, guncelfark, fiyat, newbakiye, buydate, islem)
gui.updateGuiData(lif, cooldown, guncelislem)
else:
gui.updateGuiData(lif, cooldown, lastaction)
src.after(5000, main)
src.mainloop()
main()
#src.mainloop()
#bot.polling()
My actual code is something around 450 lines, so I think pasting it here would be a waste of space. Though, I can do that if it helps you help me more easily. Anyway, the above code works perfectly with a single thread which is created by src.mainloop().
In the project, what I'm trying to do is basically a trading bot. To help the user see what is going on, I created a gui using Tkinter library. I create the gui only once and I only update the data every 5 seconds.
What I want to achieve is to create a Telegram Bot which the user can interact with. For example use should be able to type /BTC-USD to get information about bitcoin-dolar. So far, I achieved to send the user every buy/sell operation of the bot in telegram. However, what I'm stuck right now is to get commands of the user since it requires me to use bot.polling() which is another thread. Wherever I put this line of code in my code, it causes GUI to "not responding".
So in simpler words, my question is how can I have a Telegram Bot interacting with a user by sending messages and getting commands, also a GUI that is updated automatically every 5 seconds?

Client-Side API for Discord (Python)

Is there a Python Client-Side API for Discord?
I don't need much, just to listen to events like getting a call or a message.
Is it possible?
Note that selfbots are against TOS, and you could be banned without warning.
Sounds like you want a selfbot.
What you might be looking for is Discord.py, many selfbots are written in that, such as:
https://github.com/appu1232/Discord-Selfbot
If you would rather not get banned, discord.py is still good for scripting bots for servers.
Ok late answer but maybe someone can benefit from it so here goes.
Never use discord.py for selfbots. Discord.py was created to work on bot accounts not user accounts. That being said, a lot of things in discord.py will flag your account.
If you want, you can use what I'm currently developing with Merubokkusu: discum: discord selfbot api wrapper
Here's the classic ping-pong example:
import discum
bot=discum.Client(token=yourtoken)
#bot.gateway.command
def pingpong(resp):
if resp.event.message:
m = resp.parsed.auto()
if m['content'] == 'ping':
bot.sendMessage(m['channel_id'], 'pong')
bot.gateway.run()
Here's a ping-pong example where you don't reply to yourself:
import discum
bot=discum.Client(token=yourtoken)
#bot.gateway.command
def pingpong(resp):
if resp.event.message:
m = resp.parsed.auto()
if m['author']['id'] != bot.gateway.session.user['id']
if m['content'] == 'ping':
bot.sendMessage(m['channel_id'], 'pong')
bot.gateway.run()
here's another example, this one appends live messages to a list:
import discum
bot=discum.Client(token=yourtoken)
messagelist = []
#bot.gateway.command
def pingpong(resp):
if resp.event.message:
messagelist.append(resp.raw)
bot.gateway.run()
Also, if you're just doing this in the terminal and don't want to reinitialize your gateway every time, you can just clear the commands you've set
bot.gateway.clearCommands()
and clear the current (gateway) session variables
bot.gateway.resetSession()
Discum is intended to be a raw wrapper in order to give the developer maximum freedom. It's also written to be relatively-simple, easy to build-on, and easy-to-use. Hope this helps someone! Happy coding!

Categories