コンピューター:MacOS w / Python3.7およびDiscordパッケージがインストールされている
サーバー:Python3.6とDiscordパッケージがインストールされたCentOS6
コードが悪いか、問題を解決するために最適化できるのではないかと思います。
class MyClient(discord.Client):
async def on_ready(self):
print('Logged on as {0}!'.format(self.user))
print(self.user.id)
print('------')
# loops through connected servers and assigns increments server count variable
server_count = 0
quote_count = 0
for guild in client.guilds:
server_count += 1
print("The server count is {}".format(server_count))
for quote in quotes:
quote_count += 1
print("There number of quotes available is: " + str(quote_count))
print('------')
while not client.is_closed():
now = datetime.strftime(datetime.now(), '%H:%M')
iter_count = 0
print("current time is: " + now)
if now == wakeup_time: # enter for-loop at specific time
for guild in client.guilds:
for channel in guild.channels:
if str(channel) == 'chat':
await channel.send('Good Morning/Afternoon/Good Night. Here is today\'s random quote:')
await channel.send('```' + str(random.choice(quotes)).strip('[]') + '```')
print("{} Server Greeted.").format(guild.name)
iter_count += 1
if iter_count == server_count:
await asyncio.sleep(7200) # puts loop on hold for 1 hour
else:
await asyncio.sleep(10)
ローカルで行っていること:各discordサーバーの#chatチャネルに1回投稿してから、関数を2時間スリープさせます。ボットは4つの不和サーバーに接続されています。(これが私がやりたいことです)。
CentOS Linuxサーバーでの動作:サーバーの1つだけの#chatチャネルに5回投稿してから、関数を2時間スリープさせます。
質問:コードを最適化してサーバーをループし、チャットチャネルに1日1回投稿するためのより良い方法はありますか?
個人的には、これにはバックグラウンドタスクを使用します。また、guild.channels
useを使用する代わりにguild.text_channels
。コードにいくつか変更を加えました。これがお役に立てば幸いです。
class MyClient(discord.Client):
async def start_task(self):
while not client.is_closed():
now = datetime.strftime(datetime.now(), '%H:%M')
iter_count = 0
print("current time is: " + now)
if now == wakeup_time: # enter for-loop at specific time
for guild in client.guilds:
for channel in guild.text_channels:
if channel.name == 'chat':
await channel.send('Good Morning/Afternoon/Good Night. Here is today\'s random quote:')
await channel.send('```' + str(random.choice(quotes)).strip('[]') + '```')
print("{} Server Greeted.").format(guild.name)
iter_count += 1
if iter_count == server_count:
await asyncio.sleep(7200) # puts loop on hold for 1 hour
break
else:
await asyncio.sleep(10)
async def on_ready(self):
print('Logged on as {0}!'.format(self.user))
print(self.user.id)
print('------')
# loops through connected servers and assigns increments server count variable
quote_count = 0
print("The server count is {}".format(len(client.guilds)))
for quote in quotes:
quote_count += 1
print("There number of quotes available is: " + str(quote_count))
client.loop.create_task(start_task())
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加