我最近一直在研究discord机器人,我想创建一个命令,该命令从给定阵列发送 random 照片。目前,我有以下代码:
[Command("sendpic"), Summary("")]
public async Task SendPic()
{
string[] RandomPic = { "https://images.unsplash.com/photo-1536746803623-cef87080bfc8?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1000&q=80",
"https://s3.amazonaws.com/artallnight/static/files/2018/08/14154730/back-1024x532.jpg",
"https://www.abc.net.au/news/image/9776766-3x2-700x467.jpg",
"https://static1.squarespace.com/static/58d2d1d003596ef5151dd694/t/5911277b893fc011d4e8543d/1494296445782/stars2.jpg?format=1500w"
};
Random random = new Random();
int randomNumber = random.Next(0, 3);
EmbedBuilder d = new EmbedBuilder();
d.WithColor(120, 40, 23);
if (randomNumber == 1)
{
await Context.Channel.SendMessageAsync(RandomPic[1]);
} else if (randomNumber == 2) {
await Context.Channel.SendMessageAsync(RandomPic[2]);
} else if (randomNumber == 3){
await Context.Channel.SendMessageAsync(RandomPic[3]);
} else {
await Context.Channel.SendMessageAsync(RandomPic[0]);
}
}
但是它似乎不起作用,因为每当我调用“ sendpic”命令时它仅发送1张图片。如何使它从数组发送给定的图片(每次调用都发送一张?)
答案 0 :(得分:1)
问题是您每次调用命令时都在创建Random
的新实例。此类不打算那样使用。
您应该在SendPic()
方法范围之外拥有一个静态变量,如下所示:
public class YourModule : ModuleBase<SocketCommandContext>
{
private static readonly Random random = new Random();
//Your commands here
}
然后我将像这样使用它:
[Command("sendpic"), Summary("")]
public async Task SendPic()
{
string[] RandomPic =
{
"https://images.unsplash.com/photo-1536746803623-cef87080bfc8?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1000&q=80",
"https://s3.amazonaws.com/artallnight/static/files/2018/08/14154730/back-1024x532.jpg",
"https://www.abc.net.au/news/image/9776766-3x2-700x467.jpg",
"https://static1.squarespace.com/static/58d2d1d003596ef5151dd694/t/5911277b893fc011d4e8543d/1494296445782/stars2.jpg?format=1500w"
};
int randomNumber = random.Next(0, RandomPic.Length);
EmbedBuilder d = new EmbedBuilder();
d.WithColor(120, 40, 23);
await Context.Channel.SendMessageAsync(RandomPic[randomNumber]);
}
顺便说一句,您不需要按数字检查结果。它的升级效果不佳(可以想象检查1到1000之间的数字)。
检查如何使RandomPic.Length
成为randomNumber
的上限,如何删除if
语句并直接调用RandomPic[randomNumber]
(这将检索{的randomNumber
位置的元素{1}}数组。