So i have working (on windows) python code:
import asyncio
import nest_asyncio
import discord
import credentials
discord_client = None
loopHoleChannel = None
task_discord = None
telegram_client = None
task_telegram = None
class MyDiscordClient(discord.Client):
async def on_ready(self):
global loopHoleChannel
loopHoleChannel = self.get_channel(1015386432900182056)
def handle_discord():
print('Start:Discord.')
global discord_client
discord_client = MyDiscordClient(intents=discord.Intents.default())
discord_client.run(credentials.TOKEN)
print('Complete:Discord.')
async def async_main():
global task_discord
task_discord = asyncio.create_task(handle_discord())
await task_discord
def main():
nest_asyncio.apply()
asyncio.run(async_main())
main()
But when i try to run it on termux(without root) i get this:
[Exception in callback <TaskStepMethWrapper object at 0x7b3e23db40>()
handle: <Handle <TaskStepMethWrapper object at 0x7b3e23db40>()>
Traceback (most recent call last):
File "/data/data/com.termux/files/usr/lib/python3.10/asyncio/events.py", line 80, in _run
self._context.run(self._callback, *self._args)
RuntimeError: Cannot enter into task <ClientEventTask state=pending event=on_ready coro=<bound method MyDiscordClient.on_ready of <__main__.MyDiscordClient object at 0x7b3e1f24a0>>> while another task <Task pending name='Task-1' coro=<async_main() running at /data/data/com.termux/files/usr/RedsFiles/DiscordBots/TelegramToDiscordBot/main.py:33>> is being executed.]
Well it's almost obvious that problem is in [nest_asyncio
] but without it it wont work.
Question:
Is i'm right about [nest_asyncio
] and if i'm right how i can make it work without it?
Accorsing to this issue it's a problem with tasks not veing patched on linux.
The simplest way to fix this would be to use discord.py's setup_hook
function to run your coroutines alongside the discord bot:
import discord
from discord.ext import commands
class MyBot(commands.Bot):
async def setup_hook(self):
print("setting up some stuff...")
#TODO: Put your other async code here!
def on_ready(self):
print("ready")
bot = MyBot(
command_prefix="/",
intents=discord.Intents.default()
)
bot.run("your-token")