我有一个问题,当我使用 discord.utils.get(bot.voice_clients, guild=guild) 时,它返回 None,即使它已连接。我想让机器人重新连接到语音通道,因为机器人在大约 3-4 小时后被踢了。我尝试使用包含要重新连接的频道名称的文件让它重新连接到频道。
import discord
from discord.ext import commands
from discord.utils import get
import asyncio
import os
import nacl
from keep_alive import keep_alive
bot = commands.Bot(command_prefix='!')
@bot.event
async def on_ready():
print('Logged in as {0.user}'.format(bot))
@bot.command(aliases=['shreksophone'])
async def shrek(ctx, *, join_channel: str=None):
voice = get(bot.voice_clients, guild=ctx.guild)
global guild_for_reconnect, guild_for_reconnect_voice_channels
guild_for_reconnect = str(ctx.guild)
guild_for_reconnect_voice_channels = ctx.guild.voice_channels
guild_id = str(ctx.guild.id)
author_id = str(ctx.author.id)
async def shrek_repeat(ctx):
f = open('shrek_counter', 'r+')
counter = f.read()
new_counter = int(counter) + 1
f.seek(0)
f.truncate()
f.write(str(new_counter))
f.close()
voice.play(discord.FFmpegPCMAudio('songs/1 hour of shreksophone.m4a'), after=lambda e: asyncio.run(shrek_repeat(ctx)))
if not os.path.exists(guild_id):
f = open(guild_id, 'w')
f.write(author_id)
f.close()
f = open(guild_id, 'r')
session_author = f.read()
f.close()
if session_author == author_id:
if voice is None:
if join_channel is None:
if ctx.author.voice:
channel = ctx.message.author.voice.channel
await channel.connect()
await ctx.send('Playing shreksophone now in "' + channel.name + '" repeatedly.')
print('Playing shreksophone now repeatedly in ' + ctx.guild.name + '.')
voice = get(bot.voice_clients, guild=ctx.guild)
voice.play(discord.FFmpegPCMAudio('songs/1 hour of shreksophone.m4a'), after=lambda e: asyncio.run(shrek_repeat(ctx)))
f = open(guild_for_reconnect + ' channel', 'w')
f.write(str(channel))
f.close()
bot.loop.create_task(voice_reconnect())
else:
await ctx.send('You have to be in a voice channel, if you want me to play shreksophone.')
print('User is not in a voice channel.')
else:
channel = get(ctx.guild.voice_channels, name=join_channel)
channel_exist = get(ctx.guild.voice_channels, name=join_channel)
while channel_exist is None:# the code here just continues with other possibilities
async def voice_reconnect():
while True:
if os.path.exists(guild_for_reconnect + ' channel'):
voice = get(bot.voice_clients, guild=guild_for_reconnect)
f = open(guild_for_reconnect + ' channel', 'r')
channel = f.read()
f.close()
channel_to_reconnect = get(guild_for_reconnect_voice_channels, name=channel)
if voice is None:# so even if the bot is connected it still returns None
await channel_to_reconnect.connect()
if voice.channel.name is not str(channel_to_reconnect):
await voice.move_to(channel_to_reconnect)
await asyncio.sleep(0.25)