给定一个连接且准备就绪的 DiscordSocketClient 和一个 Discord 频道 ID,如何向该频道发送消



我正在尝试设置自动消息。

当我设置client时,我使用:

client.Ready += OnClientReady;

从那里我开始我的Scheduler课:

private Task OnClientReady()
{
var scheduler = new Scheduler(client);
scheduler.Start();
return Task.CompletedTask;
}

看起来像这样:

public class Scheduler
{
private readonly DiscordSocketClient _client;
private static Timer _timer;
public void Start(object state = null)
{
Sender.Send(_client);
_timer = new Timer(Start, null, (int)Duration.FromMinutes(1).TotalMilliseconds, 0);
}
public Scheduler(DiscordSocketClient client)
{
_client = client;
}
}

当计时器滴答作响时,它会调用并将client传递给下面的Sender类:

public static class Sender
{
public static void Send(DiscordSocketClient client)
{
var currentLocalDateTime = SystemClock.Instance.InTzdbSystemDefaultZone().GetCurrentLocalDateTime();
var elapsedRotations = new List<Rotations>();
using (var db = new GOPContext())
{
elapsedRotations = db.Rotations
.Include(r => r.RotationUsers)
.Where(r => r.LastNotification == null ||
Period.Between(r.LastNotification.Value.ToLocalDateTime(),
currentLocalDateTime).Hours >= 23)
.ToList();
}
foreach (var rotation in elapsedRotations)
{
var zone = DateTimeZoneProviders.Tzdb.GetZoneOrNull(rotation.Timezone);
var zonedDateTime = SystemClock.Instance.InZone(zone).GetCurrentZonedDateTime();
if (zonedDateTime.Hour != 17)
continue;
//I need to send a message to the channel here.
//I have access to the connected / ready client, 
//and the channel Id which is "rotation.ChannelId"
}
}
}

我试过像这样获取频道:

var channel = client.GetChannel((ulong) rotation.ChannelId);

这给了我一个SocketChannel,也像这样:

var channel = client.Guilds
.SelectMany(g => g.Channels)
.SingleOrDefault(c => c.Id == rotation.ChannelId);

这给了我一个SocketGuildChannel. 这些都没有给我直接向频道发送消息的选项。 我尝试研究如何做到这一点,但没有发现任何东西...... 文档似乎没有任何这方面的示例...

这似乎是一件简单的事情,但我对此很聪明。 有人知道怎么做吗?

这是因为SocketGuildChannelSocketChannel都可以是语音或文本通道。

相反,你想要ISocketMessageChannelIMessageChannelSocketTextChannel

要获得这个,您可以简单地投射您正在获得的SocketChannel

var channel = client.GetChannel((ulong) rotation.ChannelId);
var textChannel = channel as IMessageChannel;
if(textChannel == null)
// this was not a text channel, but a voice channel
else
textChannel.SendMessageAsync("This is a text channel");

最新更新