【发布时间】:2018-01-06 06:29:06
【问题描述】:
我目前正在制作 Discord 机器人。我希望它能够使用特定查询访问 API,然后在聊天中显示响应。为此,我做了这个命令:
commands.CreateCommand("card").Parameter("user", ParameterType.Unparsed).Do(async (e) =>
{
string message = e.Args[0];
await e.Channel.SendMessage("https://omgvamp-hearthstone-v1.p.mashape.com/cards/" + message + "?collectible=1");
var r = await Get<RootObject>("https://omgvamp-hearthstone-v1.p.mashape.com/cards/" + message + "?collectible=1");
Console.Write("Hold it!\n");
await e.Channel.SendMessage(r.img);
});
以及它引用的函数:
public async Task<RootObject> Get<RootObject>(string url)
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.TryAddWithoutValidation("X-Mashape-Key", "xxxxx");
client.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "application/json");
Console.Write("Hang on!\n");
var json = await client.GetStringAsync(url);
Console.Write("Not so fast!\n");
return JsonConvert.DeserializeObject<RootObject>(json);
}
}
但是当我发送命令时,它只发回第一个链接以及挂起和不太快的消息。我想要的消息,r.img,只是没有发送。如何更改代码以响应我想要的信息?
顺便说一句,回复:
[
{
"cardId":"EX1_572",
"dbfId":"1186",
"name":"Ysera",
"cardSet":"Classic",
"type":"Minion",
"faction":"Neutral",
"rarity":"Legendary",
"cost":9,
"attack":4,
"health":12,
"text":"At the end of your turn, add_a Dream Card to_your hand.",
"flavor":"Ysera rules the Emerald Dream. Which is some kind of green-mirror-version of the real world, or something?",
"artist":"Gabor Szikszai",
"collectible":true,
"elite":true,
"race":"Dragon",
"playerClass":"Neutral",
"img":"http://media.services.zam.com/v1/media/byName/hs/cards/enus/EX1_572.png",
"imgGold":"http://media.services.zam.com/v1/media/byName/hs/cards/enus/animated/EX1_572_premium.gif",
"locale":"enUS"
}
]
还有 RootObject.cs:
namespace DiscordBot
{
public class RootObject
{
public string cardId { get; set; }
public string dbfId { get; set; }
public string name { get; set; }
public string cardSet { get; set; }
public string type { get; set; }
public string faction { get; set; }
public string rarity { get; set; }
public int cost { get; set; }
public int attack { get; set; }
public int health { get; set; }
public string text { get; set; }
public string flavor { get; set; }
public string artist { get; set; }
public bool collectible { get; set; }
public bool elite { get; set; }
public string race { get; set; }
public string playerClass { get; set; }
public string img { get; set; }
public string imgGold { get; set; }
public string locale { get; set; }
}
}
【问题讨论】:
-
这和c#无关,是你使用的库有问题。我建议你调试你的代码,看看发生了什么
-
@CamiloTerevinto 我在所有语句中都暂停了,虽然它确实在 Get
函数中暂停,并且在执行所述函数时,它不会在之后的语句中暂停。 Here's where it paused, the second and third pause from the top didn't register. -
@CamiloTerevinto 不过调试数据中没有什么奇怪的,至少没有什么明显的。
-
Get 函数是否正常返回?在我看来, JsonConvert 可能会引发异常。查看输出窗口中的线索
-
@CamiloTerevinto 嘿,你似乎是对的。输出消息是:抛出异常:Newtonsoft.Json.dll 中的“Newtonsoft.Json.JsonSerializationException”抛出异常:mscorlib.dll 中的“Newtonsoft.Json.JsonSerializationException”
标签: c# discord discord.net