Discord.py || How to loop a part of Program infinite times without crashing it eventually? - python

I am Trying to Make a 24/7 Streaming Discord Bot using while(True): Infinite Loop,
But I think that the while(True): will get crashed by the OS (Using Heroku for Hosting) or Some kind of threads problem
#commands.command(name='play',aliases=["p"])
async def _play(self, ctx: commands.Context):
i = 0
while(True): #Infinite While Loop
search = URL[i] #URL is the List of Musics I What to Stream 24/7
if not ctx.voice_state.voice:
await ctx.invoke(self._join) #joins the voice channel if not in voice channel previously
async with ctx.typing():
try:
source = await YTDLSource.create_source(ctx, search, loop=self.bot.loop)
#Sets the Status of the Bot to What Music it is Playing Currently
await self.bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=f"{source.title}"))
except YTDLError as e:
await ctx.send('An error occurred while processing this request: {}'.format(str(e)))
else:
song = Song(source)
await ctx.voice_state.songs.put(song) #Enqueue the Song
i = (i + 1) % len(URL) # Updates the Index of URL
await asyncio.sleep(source.DURATION) #Gets the Lenght of the Music in int and Sleeps
I thought of using Asyncio Event Loops but Can't Figure it Out How to Use it Because my Function Has Parameters/Arguments like context (ctx)
I have Also thought of Cleaning the Memory stack after each songs play... But is it possible ??? If yes can we use it to fix my problem
So Is there anyway to Loop The above Mentioned Block or Code Infinitely without crashing it eventually
Thanks in advance !!!
I have a Out of Topic Query... Can we Use the ability of Context (ctx) without passing it as a Argument.
If we Can then I might be able to use asyncio_event_loop, I suppose

Related

How to run discord.py interactively in jupyter notebook?

In discord.py, you can initialize a Client, and run it with client.run(). But the function never returns.
What if I just want to just retrieve some message history then use it in jupyter notebook?
#bot.command()
async def history(ctx):
counter = 0
messageList=[]
async for message in ctx.channel.history(limit = 100):
print(message.author, message.content)
counter += 1
messageList.append(message)
await ctx.send(f'total **{counter}** messages in this channel.')
# How to return the messageList to my jupyter notebook cell and I start playing with the messageList?
How to return the messageList?
There isn't a good way to do this. discord.py is designed to be started once and run until your program terminates since all of the internal objects are destroyed upon closure of the bot, which makes starting the bot back up again nearly impossible. And it is not possible to "pause" discord.py and run your code then resumes discord.py afterwards, because Discord API communicates via web sockets, which relies on a constant stream of heartbeats and acks.
A possible workaround would be to:
Use a single event loop through out the code.
Use loop.run_until_complete() to start the bot's internal loop.
Create a new Client every time you need to run the bot.
Create an on_ready event handle that fetches the information.
Downside is that you won't be able to interact with the Message objects (ie. delete, edit, etc), they will be view only.
Example:
import asyncio
import discord
TOKEN = "YOURBOTTOKEN"
loop = asyncio.get_event_loop()
def get_message_list(token, channel_id):
client = discord.Client(loop=loop)
message_list = []
#client.event
async def on_ready():
nonlocal message_list
channel = client.get_channel(channel_id)
if not channel: # incase the channel cache isn't fully populated yet
channel = await client.fetch_channel(channel_id)
async for message in channel.history(limit=100):
message_list.append(message)
await client.close()
async def runner():
try:
await client.start(token)
finally:
if not client.is_closed():
# Incase the bot was terminated abruptly (ie. KeyboardInterrupt)
await client.close()
loop.run_until_complete(runner())
return message_list
message_list = get_message_list(TOKEN, channel_id=747699344911712345)
print("Message list for channel #1:", message_list)
# ... do stuff with message_list
message_list = get_message_list(TOKEN, channel_id=747699344911754321)
print("Message list for channel #2:", message_list)
# ... do more stuff with message_list
# Finally closes the event loop when everything's done
loop.close()
Instead of doing this, I'd recommend you to find another solution to the task you're trying to accomplish.

Discord.py Bot Takes too Long to Respond

Goal:
I'm developing a discord bot which scans a url every 5 seconds or so, checks for a specified change on that webpage, and will send a message in the discord channel if that change occurs. I've done this by sending the url to the bot using an if statement in on_message. The url is then passed to a tasks.loop() function, where it is scanned and processed in another function for the change.
Problem:
I'd like to be able to send a message in the discord channel which quickly ends the process taking place in the tasks.loop(), so that I can pass it a different url to scan using the on_message function. In its current form, it works-- just very slowly. From the time the cancel trigger is sent, it takes around 3 minutes to send the verification message that the process has been cancelled. I need to make this 5 seconds or less. For what its worth, the bot is kept running using replit and uptime robot, but I am sure that the long response time is not related to the frequency the repl is awoken by uptime robot.
Code:
My code is much more complex and riddled with obscurely named variables, so here is a much simpler snippet of code with the same general structure.
client = discord.Client()
channel = client.get_channel(CHANNEL_ID)
#tasks.loop()
async def myloop(website, dataframe):
channel = client.get_channel(CHANNEL_ID)
try:
# iteratively scrape data from a website for
# a predefined change in the dataframe
if change = True:
await channel.send(notification)
except:
pass
#client.event
async def on_message(message):
channel = client.get_channel(CHANNEL_ID)
msg = message.content
if msg.startswith('track'):
website = msg[6:]
await channel.send('Now tracking '+str(website))
myloop(website,df)
if msg.starswith('stop'):
myloop.cancel()
await channel.send('Done tracking, awaiting orders.')
Attempted Solutions:
I have tried using some forms of threading, which I am very new to, and I haven't found a way to make it work any faster. Any suggestions or solutions would be greatly appreciated! I've been combing the web for help for quite some time now.
Looks like you could use client.loop.create_task to create asyncio task objects, and their cancel method to immediately cancel those asyncio tasks at the right time, e.g.
import asyncio
from replit import db
_task = None
async def myloop():
website = db['website']
dataframe = db['dataframe']
channel = client.get_channel(CHANNEL_ID)
while not client.is_closed():
await asyncio.sleep(5)
try:
# iteratively scrape data from a website for
# a predefined change in the dataframe
if change:
await channel.send(notification)
except:
pass
#client.event
async def on_message(message):
global _task # This gives the function access to the variable that was already created above.
msg = message.content
if msg.startswith('track'):
website = msg[6:]
await message.channel.send('Now tracking '+str(website))
db['website'] = website
db['dataframe'] = df
if _task is not None:
_task.cancel()
_task = client.loop.create_task(myloop())
if msg.startswith('stop'):
if _task is not None:
_task.cancel()
_task = None
await message.channel.send('Done tracking, awaiting orders.')
The argument create_task takes is a coroutine that takes no arguments, so the website URL and dataframe need to be accessible to the function a different way (I'm not sure which way you would prefer or would be best; using replit's db is just an example).
With this approach, you should be able to use track again to change which website is being monitored without using stop in between.
More details in the docs:
discord.Client.loop
loop.create_task
Task.cancel
asyncio.sleep
discord.Client.is_closed
Replit db

discord.ext problems with sending in right channel and setting status

I'm using discord.py, and from there the discord.ext module. I have a quite long selenium code running in a while True loop. Here's part of it:
#bot.command()
async def start(ctx):
driver.install_addon(r'some_extension.xpi')
channel = bot.get_channel(791352165393498203)
user = bot.get_user(257428782233812993)
while True:
await bot.change_presence(status=Status.online)
driver.get('some_link')
driver.maximize_window()
time.sleep(5)
try:
driver.find_element_by_xpath('//*[#id="pageSize"]').click()
except NoSuchElementException:
await ctx.channel.send(f" We had an Exception, please go check")
time.sleep(60)
driver.refresh()
time.sleep(5)
driver.find_element_by_xpath('//*[#id="pageSize"]').click()
time.sleep(1)
await ctx.channel.send(f"Problem solved")
Most of this code works fine, but there are two main problems, and I don't get an exception.
Firstly, the await ctx.channel.send(f"We had an Exception, please go check") should be sent in the channel I stated above, but it
doesn't. pycharm says that the channel variable is never used,
which shouldn't be the case.
Secondly, the await bot.change_presence(status=Status.online) doesn't keep the bot
permanently displayed as online.
Just use channel.send() without ctx, ctx is a bunch of info about used command (author, channel, etc.).
You don't need to change status to online, it's automatically setting when you launch the bot.
Oh, and i recommend to use asyncio.sleep() instead of time.sleep() because, when u use time.sleep() the bot will stop working in this time, and will not responding to any command/event.

discord.py way to use the bot in a new thread

I'm making my discord.py bot, and I want a way to send custom messages. I tried using on_message but kept having error about threading.
#bot.event
async def on_ready():
print(f'{bot.user.name} is now on Discord!')
#Here I want a loop that asks for input, then, if it gets it, the bot sends it.
I've tried using Thread's, but I can't await in a thread.
#I want to do somthing like:
channel = bot.get_channel(my_channel_id)
while True:
msg = input("Bot: ")
await channel.send(msg)
Thanks for all your answers!
EDIT:
I'm having trouble getting your solutions to work, and I'm pretty sure it's my fault. Is there any way for the bot to run normally, but while it does, there is a loop asking for input and sending it to discord as the bot when it gets it.
Like a working version of this?:
c = bot.get_channel(my_channel_id)
while True:
message = input("Bot: ")
await c.send(message)
AFAIK There is no async equivalent of input() in standard library. There are some workarounds for it, here is my suggestion that I think is the cleanest:
Fire up a thread when your program starts that you can run the blocking input() call in it. I used an executor because asyncio has a handy function to communicate with executor of any kind. Then from async code schedule a new job in executor and wait for it.
import asyncio
from concurrent.futures.thread import ThreadPoolExecutor
async def main():
loop = asyncio.get_event_loop()
while True:
line = await loop.run_in_executor(executor, input)
print('Got text:', line)
executor = ThreadPoolExecutor(max_workers=1)
asyncio.run(main())

Why is my discord bot only executing my command one time and one time only?

I'm in the process of finishing a simple sound clip Discord bot I made by recycling a basic music bot example in python. All I want the bot to do is enter the voice channel of the user who called the command (!womble), play a random sound clip from a folder of sound clips, then leave the voice channel.
"Simple, right?" Of course it isn't, not with this API apparently.
After a BUNCH of trial and error, looking to at least 3 API revisions I got the bot to actually perform the command.....one time. Any further prompts of the command are met with crickets. I can do a !summon and it bring the bot into the channel, but the !womble command no longer works.
def bot_leave(self, ctx):
state = self.get_voice_state(ctx.message.server)
coro = state.voice.disconnect()
fut = asyncio.run_coroutine_threadsafe(coro, state.voice.loop)
try:
fut.result()
except:
# an error happened sending the message
pass
#commands.command(pass_context=True, no_pm=True)
async def womble(self, ctx):
state = self.get_voice_state(ctx.message.server)
opts = {
'default_search': 'auto',
'quiet': True,
}
if state.voice is None:
success = await ctx.invoke(self.summon)
if not success:
return
try:
random_clip = clip_dir + "\\" + random.choice(os.listdir(clip_dir))
player = state.voice.create_ffmpeg_player(random_clip, after=lambda: self.bot_leave(ctx))
player.start()
except Exception as e:
fmt = 'An error occurred while processing this request: ```py\n{}: {}\n```'
await self.bot.send_message(ctx.message.channel, fmt.format(type(e).__name__, e))
I have tried going into the python chat is the Discord API server, but much like my bot, I'm met with crickets. (Guess that's what I get trying to seek support from a chat that already has 4 conversations going.)
I'm guessing you might not need help anymore but just in case you should try removing the coroutine.result() and run it directly. I.e change:
def bot_leave(self, ctx):
state = self.get_voice_state(ctx.message.server)
coro = state.voice.disconnect()
fut = asyncio.run_coroutine_threadsafe(coro, state.voice.loop)
try:
fut.result()
except:
# an error happened sending the message
pass
to:
def bot_leave(self, ctx):
state = self.get_voice_state(ctx.message.server)
coro = state.voice.disconnect()
try:
asyncio.run_coroutine_threadsafe(coro, state.voice.loop)
except:
# an error happened sending the message
pass
That's the only thing I could think of seeing your code snippet, but the problem may lie elsewhere in the code.

Categories