write some Data on disk during an async function #8278
-
hello ! I need to write some Data during an async function but in this sample the script refuse to write the variable value ( import discord
import asyncio
class MyClient(discord.Client):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# create the background task and run it in the background
self.bg_task = self.loop.create_task(self.my_background_task())
async def on_ready(self):
print('Logged in as')
print(self.user.name)
print(self.user.id)
print('------')
async def my_background_task(self):
await self.wait_until_ready()
counter = 0
channel = self.get_channel(979869063905939456) # channel ID goes here
while not self.is_closed():
counter += 1
with open('readme.txt', 'w') as f:
f.write(counter)
await channel.send(counter)
await asyncio.sleep(2) # task runs every 60 seconds
intents = discord.Intents.default()
intents.messages = True
client = MyClient(intents=intents)
client.run('tokenhere')``` |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Your background task is running into an error because you can not pass an integer to the >>> with open('example.txt', 'w') as f:
... f.write(1)
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
TypeError: write() argument must be str, not int You will have to convert your counter variable to a string when writing it to the file instead. To see this sort of error you might want to wrap your code in a try except block to be able to log it, or you can base your code off of the other background task example using the tasks extension, as it will print/log errors by default. |
Beta Was this translation helpful? Give feedback.
Your background task is running into an error because you can not pass an integer to the
write
function:You will have to convert your counter variable to a string when writing it to the file instead.
To see this sort of error you might want to wrap your code in a try except block to be able to log it, or you can base your code off of the other background task example using the tasks extension, as it will print/log errors by default.