Python Threading Error: This event loop is already running - python

If your looking to run the code...make sure to do pip install discord.py
I have the following three python files which work together to connect to a discord server
Launch.py
from Sender import *
from Reciever import *
class Launcher:
def startThreads(sendOB, recOB, username):
threads = []
recThread = threading.Thread(target=recOB.main, args=())
sendThread = threading.Thread(target=sendOB.main, args=(username))
threads.append(sendThread)
threads.append(recThread)
for i in range(2):
threads[i].start()
for i in range(2):
threads[i].join()
def launcherMain(self):
username = input("Enter your username: ")
theSender = Send()
theReciever = Recieve()
Launcher.startThreads(theSender, theReciever, username)
launchOB = Launcher()
launchOB.launcherMain()
Reciever.py
import discord, threading, asyncio
client = discord.Client()
class Recieve:
index = None
#client.event
async def on_message(message):
#Run through decrypter here
if message.author == client.user:
return
Recieve.index = message.content.find(": ")
print(str(Recieve.index))
#print(message.content[0:Recieve.index] + "~-#" + message.content[Recieve.index + 2:len(message.content))
#client.event
async def on_ready():
print("Reciever Ready to go")
print('---------')
def main(self):
client.run('TokenErasedForSecurity')
#rec = Recieve()
#rec.main()
Sender.py
import discord, threading, asyncio
client = discord.Client()
class Send:
username = ""
async def messageSender():
channel = discord.Object(id='IdErasedForSecurity')
while True:
messageToSend = Send.username + ": "
messageToSend += input(Send.username + '~->')
await client.send_message(channel, messageToSend)
#client.event
async def on_ready():
print("Sender Ready to go")
print('---------')
client.loop.create_task(Send.messageSender())
def main(self, theUsername):
Send.username = theUsername
client.run('TokenErasedForSecurity')
Launch.py runs sender and reciever using threads, but when I run launch.py I get this exception
Enter your username: a Exception in thread Thread-1: Traceback (most
recent call last): File "C:\Program
Files\Python36\lib\site-packages\discord\client.py", line 519, in run
self.loop.run_until_complete(self.start(*args, **kwargs)) File "C:\Program Files\Python36\lib\asyncio\base_events.py", line 454, in
run_until_complete
self.run_forever() File "C:\Program Files\Python36\lib\asyncio\base_events.py", line 408, in run_forever
raise RuntimeError('This event loop is already running') RuntimeError: This event loop is already running
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File "C:\Program
Files\Python36\lib\threading.py", line 916, in _bootstrap_inner
self.run() File "C:\Program Files\Python36\lib\threading.py", line 864, in run
self._target(*self._args, **self._kwargs) File "C:\Users\user\Desktop\Discord\HopeForBetter\Reciever.py", line 26,
in main
client.run('MzAzNjUyODYwNjY1NTI4MzIx.C9bPOA.4ISE_jmY1BYlPq937zGpjISuvAI')
File "C:\Program Files\Python36\lib\site-packages\discord\client.py",
line 534, in run
self.loop.close() File "C:\Program Files\Python36\lib\asyncio\selector_events.py", line 107, in close
raise RuntimeError("Cannot close a running event loop") RuntimeError: Cannot close a running event loop
The only thing I have been able to come up with is that it is causing an exception since both threads are accessing the same file, but this doesn't seem plausible enough but I am also a novice at threading.

Related

Run a discord bot in async together with a loop

I am trying to communicate a discord bot with an arduino board. The problem is being able to read, and write to serial. I am doing it by running an infinite loop that reads if the button on the arduino is pressed. And if it is it sends a message saying so. <this works
the problem is when I try to read the messages sent to the bot. They just don't trigger on_message(message) and they go ignored. Can ya'll help here?
`
import serial
import discord
import time
button = "off"
lastButton = "off"
def write(x):
ser.write(bytes(x, 'utf-8'))
ser = serial.Serial(port = f"COM3")
ser.flushInput()
client = discord.Client(intents=discord.Intents.default())
#client.event
async def on_message(message):
print(message)
if message.author == client.user:
return
if message.content.startswith('$hello'): #the problem is that this only runs for the message sent by loop
await message.channel.send('Hello!') #it ignores any other message. Also every 30 secs it sends a WARN
#client.event
async def on_ready():
print(f'\n{client.user} connected!\n')
await loop()
Token = "My token"
async def loop():
global button_reading
global button
global default
global lastButton
while 1 == 1:
try:
reading = ser.readline()
reading = reading.decode('utf-8').split("\r")[0]
button_reading = reading.split(".")[0]
if reading == "on" or reading == "off":
button = reading
except Exception:
pass
if button != lastButton:
default = client.get_channel(1037184542223642636)
await default.send(f"button is now {button}!") #this works
lastButton = button
client.run(disToken)
[![enter image description here](https://i.stack.imgur.com/UIdTl.png)](https://i.stack.imgur.com/UIdTl.png) The WARN is:
2022-11-02 00:00:57 WARNING discord.gateway Shard ID None heartbeat blocked for more than 30 seconds.
Loop thread traceback (most recent call last):
File "c:\Users\Gabocota\OneDrive - ITESO\programacion\proyecto\i.py", line 65, in <module>
client.run(disToken)
File "C:\Users\Gabocota\OneDrive - ITESO\programacion\proyecto\lib\site-packages\discord\client.py", line 828, in run
asyncio.run(runner())
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 636, in run_until_complete
self.run_forever()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\lib\asyncio\windows_events.py", line 321, in run_forever
super().run_forever()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 603, in run_forever
self._run_once()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 1899, in _run_once
handle._run()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\lib\asyncio\events.py", line 80, in _run
self._context.run(self._callback, *self._args)
File "C:\Users\Gabocota\OneDrive - ITESO\programacion\proyecto\lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "c:\Users\Gabocota\OneDrive - ITESO\programacion\proyecto\i.py", line 29, in on_ready
await loop()
File "c:\Users\Gabocota\OneDrive - ITESO\programacion\proyecto\i.py", line 40, in loop
reading = ser.readline()
File "C:\Users\Gabocota\OneDrive - ITESO\programacion\proyecto\lib\site-packages\serial\serialwin32.py", line 288, in read
result_ok = win32.GetOverlappedResult(
`
I don't know what is "blocking" it
Thanks in advance

Azure Async Python SDK Error when iterating through VM list

I made a simple asynchronous python program to get the list of all Virtual Machines in a subscription. But I'm getting an error when iterating through the list.
The complete program:
from azure.identity.aio import AzureCliCredential
from azure.mgmt.compute.aio import ComputeManagementClient
from azure.mgmt.network.aio import NetworkManagementClient
from azure.mgmt.web.aio import WebSiteManagementClient
from azure.mgmt.sql.aio import SqlManagementClient
import asyncio
credential = AzureCliCredential()
compute_client = ComputeManagementClient(credential, "XXXXX")
web_client = WebSiteManagementClient(credential, "XXXX")
async def get_as_list():
as_list = web_client.web_apps.list()
async for _as in as_list:
pass
return as_list
async def get_vm_list():
vm_list = compute_client.virtual_machines.list_all()
async for vm in vm_list:
pass
return vm_list
async def main():
await get_as_list()
await get_vm_list()
if __name__ == '__main__':
asyncio.run(main())
The Error:
Traceback (most recent call last):
File "c:\Users\Kristian-Laptop\Desktop\Work\Azure Inventory\Inventory with UI\test.py", line 32, in <module>
asyncio.run(main())
File "C:\Users\Kristian-Laptop\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\Kristian-Laptop\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 647, in run_until_complete
return future.result()
File "c:\Users\Kristian-Laptop\Desktop\Work\Azure Inventory\Inventory with UI\test.py", line 28, in main
await get_vm_list()
File "c:\Users\Kristian-Laptop\Desktop\Work\Azure Inventory\Inventory with UI\test.py", line 22, in get_vm_list
async for vm in vm_list:
File "C:\Users\Kristian-Laptop\.virtualenvs\Inventory_with_UI-ioU1jGkq\lib\site-packages\azure\core\async_paging.py", line 163, in __anext__
return await self.__anext__()
File "C:\Users\Kristian-Laptop\.virtualenvs\Inventory_with_UI-ioU1jGkq\lib\site-packages\azure\core\async_paging.py", line 157, in __anext__
self._page = await self._page_iterator.__anext__()
File "C:\Users\Kristian-Laptop\.virtualenvs\Inventory_with_UI-ioU1jGkq\lib\site-packages\azure\core\async_paging.py", line 99, in __anext__
self._response = await self._get_next(self.continuation_token)
File "C:\Users\Kristian-Laptop\.virtualenvs\Inventory_with_UI-ioU1jGkq\lib\site-packages\azure\mgmt\compute\v2022_08_01\aio\operations\_virtual_machines_operations.py", line 1486, in get_next
request = prepare_request(next_link)
File "C:\Users\Kristian-Laptop\.virtualenvs\Inventory_with_UI-ioU1jGkq\lib\site-packages\azure\mgmt\compute\v2022_08_01\aio\operations\_virtual_machines_operations.py", line 1471, in prepare_request
_next_request_params["api-version"] = self._config.api_version
AttributeError: 'ComputeManagementClientConfiguration' object has no attribute 'api_version'
No problem iterating through the Web app list. I'm only getting the error with the VM list.

futures timeout error in the telegram bot, concurrent.futures._base.TimeoutError

I have created a telegram bot. where I am asking the users to send the location.
import aioschedule as schedule
import asyncio
from asyncio import futures
#bot.on(events.CallbackQuery(pattern=r'sendloc'))
async def sendlocation(event):
sender = await event.get_input_sender()
my_user = await bot.get_entity(sender.user_id)
userId = my_user.id
async with bot.conversation(userId) as conv:
await conv.send_message('receiving', buttons=[Button.request_location(text='send Location', resize=10)])
try:
response = await conv.get_response()
except futures.TimeoutError as e:
await conv.cancel_all()
return
conv.send_message('location accepted')
async def methodToSendLocation():
users = pd.read_csv('telegramId.csv')
for user in users['Telegram ID']:
try:
await bot.send_message(user, 'send location', buttons=Button.inline('sendloc'))
except ValueError as e:
print('Error occurred for user: {telId}'.format(telId=user))
def main():
'''start the bot'''
bot.start()
schedule.every().day.at("11:00").do(methodToSendLocation)
loop = asyncio.get_event_loop()
while True:
loop.run_until_complete(schedule.run_pending())
bot.run_until_disconnected()
if __name__ == '__main__':
main()
what does my program do?
It will run every day at 11:00 AM.
It will fetch the telegram Id from the CSV file and send a message to the users to send the location and we process the location.
My Query:
Sometimes there occurs a timeout error in sendlocation method of my program and recently I observed that for some users timeout error occurred within a minute after the user clicks the send Location button.
I am not able to understand why the error occurred in a very short interval.
And sometimes there has been a delay to send the location to the bot after the user clicks the send Location button.
stack trace:
Traceback (most recent call last):
File "app.py", line 118, in sendlocation
response = await conv.get_response()
File "C:\Users\Swarnim\AppData\Local\Programs\Python\Python37-32\lib\asyncio\tasks.py", line 449, in wait_for
raise futures.TimeoutError()
concurrent.futures._base.TimeoutError
Stack (most recent call last):
File "app.py", line 450, in <module>
main()
File "app.py", line 444, in main
loop.run_until_complete(schedule.run_pending())
File "/usr/lib/python3.6/asyncio/base_events.py", line 471, in run_until_complete
self.run_forever()
File "/usr/lib/python3.6/asyncio/base_events.py", line 438, in run_forever
self._run_once()
File "/usr/lib/python3.6/asyncio/base_events.py", line 1451, in _run_once
handle._run()
File "/usr/lib/python3.6/asyncio/events.py", line 145, in _run
self._callback(*self._args)
File "/home/epluser/.venv/automation/lib/python3.6/site-packages/telethon/client/updates.py", line 443, in _dispatch_update
await callback(event)
File "app.py", line 121, in sendlocation

Cannot close a running event loop discord.py

I've migrating my discord bot to use MySQL instead of storing data in json files. The only problem I got now is when I try to load the music extension of the bot...
Code:
import discord
import lavalink
from discord import Guild
from discord import User
from discord.ext import commands
# from bot import get_musicchannel
# from bot import get_prefix
from bot import mycursor
def get_musicchannel(guild: Guild):
# with open("cogs/music.json") as f:
# channels = json.load(f)
# channel: TextChannel = discord.utils.get(guild.text_channels, id=channels[str(guild.id)])
# return channel.id
sqlcommand = "SELECT channelid FROM musicchannels WHERE guildid = %s"
vals = (guild.id,)
mycursor.execute(sqlcommand, vals)
result = mycursor.fetchall()
strchannelid = str(result[0]).replace("(", "").replace(")", "").replace(",", "")
channelid = int(strchannelid)
return channelid
class Music(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.bot.music = lavalink.Client(self.bot.user.id)
self.bot.music.add_node("IP", 2333, 'PASS', 'eu', 'music-node')
self.bot.add_listener(self.bot.music.voice_update_handler, 'on_socket_response')
self.bot.music.add_event_hook(self.track_hook)
#commands.command(name="music")
async def music(self, ctx, opt, *, arg=None):
if ctx.message.channel.id != get_musicchannel(ctx.guild):
# channel = get_musicchannel(ctx.guild)
actual_channel = discord.utils.get(ctx.guild.text_channels, id=get_musicchannel(ctx.guild))
return await ctx.send(f"Music commands can only be used in the music channel ({actual_channel.mention})")
if opt == "join":
member = discord.utils.find(lambda m: m.id == ctx.author.id, ctx.guild.members)
if member is not None and member.voice is not None:
vc = member.voice.channel
player = self.bot.music.player_manager.create(ctx.guild.id, endpoint=str(ctx.guild.region))
if not player.is_connected:
player.store('channel', ctx.guild.id)
await self.connect_to(ctx.guild.id, str(vc.id))
# Unimportant code
async def track_hook(self, event):
if isinstance(event, lavalink.events.QueueEndEvent):
guild_id = int(event.player.guild_id)
await self.connect_to(guild_id, None)
async def connect_to(self, guild_id: int, channel_id: int):
ws = self.bot._connection._get_websocket(guild_id)
await ws.voice_state(str(guild_id), channel_id)
async def disconnect_from(self, guild_id: int):
ws = self.bot._connection.voice_clients
print(ws)
def setup(bot):
bot.add_cog(Music(bot))
When I try to run the bot it gives me this error:
Ignoring exception in on_ready
Traceback (most recent call last):
File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 668, in run
loop.run_forever()
File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\asyncio\windows_events.py", line 314, in run_forever
assert self._self_reading_future is None
AssertionError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 93, in _cleanup_loop
_cancel_tasks(loop)
File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 78, in _cancel_tasks
loop.run_until_complete(asyncio.gather(*tasks, return_exceptions=True))
File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\asyncio\base_events.py", line 592, in run_until_complete
self._check_running()
File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\asyncio\base_events.py", line 552, in _check_running
raise RuntimeError('This event loop is already running')
RuntimeError: This event loop is already running
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 607, in _load_from_module_spec
spec.loader.exec_module(lib)
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "D:\Ficheiros\Pastas\Tudo\Coding\Python\Projects\Server-Utils\cogs\music.py", line 11, in <module>
from bot import mycursor
File "D:\Ficheiros\Pastas\Tudo\Coding\Python\Projects\Server-Utils\bot.py", line 1383, in <module>
bot.run(TOKEN)
File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 674, in run
_cleanup_loop(loop)
File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 98, in _cleanup_loop
loop.close()
File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\asyncio\proactor_events.py", line 674, in close
raise RuntimeError("Cannot close a running event loop")
RuntimeError: Cannot close a running event loop
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 312, in _run_event
await coro(*args, **kwargs)
File "D:/Ficheiros/Pastas/Tudo/Coding/Python/Projects/Server-Utils/bot.py", line 421, in on_ready
bot.load_extension('cogs.music')
File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 664, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 610, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.music' raised an error: RuntimeError: Cannot close a running event loop
Process finished with exit code 0
The on_ready event just has bot.load_extension('cogs.music') that's where the error comes from
I don't know what can I do to make this run... Help is appreciated.

XMPP threaded receiver in Python 3

What I want to do is set up an XMPP receiver using the Slixmpp library which listens for messages throughout the script execution. I think the threading library might provide a solution so tried that.
This script is for an online PvP game and I need to receive information from the opponent continuously.
This is the code I have tried:
import time
import threading as td
import slixmpp as slix
import logging
import asyncio
my_jid = "test#xmpp.jp"
my_pass = "test"
class receiver(slix.ClientXMPP):
def __init__(self, jid, password):
slix.ClientXMPP.__init__(self, jid, password)
self.add_event_handler("session_start", self.start)
self.add_event_handler("message", self.message)
def start(self, event):
self.send_presence()
self.get_roster()
def message(self, msg):
if msg['type'] in ('chat', 'normal'):
msg.reply("Thanks for sending\n%(body)s" % msg).send()
print(msg['body'])
def function():
recv = receiver(my_jid, my_pass)
recv.connect()
recv.process()
newthread = threading.Thread(target=function)
logging.basicConfig(level="DEBUG", format='%(levelname)-8s %(message)s')
newthread.start()
input("Press Enter to continue")
This returns the following error:
Exception in thread Thread-1:
Press Enter to continueTraceback (most recent call last):
File "C:\Program Files (x86)\Python37-32\lib\threading.py", line 917, in _bootstrap_inner
self.run()
File "C:\Program Files (x86)\Python37-32\lib\threading.py", line 865, in run
self._target(*self._args, **self._kwargs)
File "C:/Users/dps/Documents/GitHub/Python-Problems/UltimateTicTacToe-scripts/xmppp.py", line 46, in good
recv = receiver(my_jid, my_pass)
File "C:/Users/dps/Documents/GitHub/Python-Problems/UltimateTicTacToe-scripts/xmppp.py", line 32, in __init__
slix.ClientXMPP.__init__(self, jid, password)
File "C:\Users\dps\venv\lib\site-packages\slixmpp\clientxmpp.py", line 70, in __init__
BaseXMPP.__init__(self, jid, 'jabber:client', **kwargs)
File "C:\Users\dps\venv\lib\site-packages\slixmpp\basexmpp.py", line 48, in __init__
XMLStream.__init__(self, **kwargs)
File "C:\Users\dps\venv\lib\site-packages\slixmpp\xmlstream\xmlstream.py", line 219, in __init__
self.disconnected = asyncio.Future()
File "C:\Program Files (x86)\Python37-32\lib\asyncio\events.py", line 644, in get_event_loop
% threading.current_thread().name)
RuntimeError: There is no current event loop in thread 'Thread-1'.
In my case executing:
newthread.daemon = True
Before calling:
newthread.start()
Works as expected creating a non-blocking thread.

Categories