我正在创建一个简单的电报机器人,它根据地理位置发送天气信息。
我希望它能像这样工作:
-
聊天中的用户类型/天气
-
Bot表示地理位置是必需的,并且会出现请求位置的自定义键盘
-
用户按下按钮共享位置并获得结果(天气信息)
一切都很好,除了一件事-若用户手动发送他的位置,机器人会做出反应,并给出天气反馈。我想让它(天气信息代码)只在聊天中发送/weather时工作。我想检查前一条消息文本是否等于“/weather”,但找不到解决方案:/
C#代码:
private static void Bot_OnMessage(object sender, MessageEventArgs e)
{
var message = e.Message;
if (message == null || message.Type != MessageType.Text) return;
try
{
switch (message.Text)
{
case "/weather":
var requestLocationKeyboard = new ReplyKeyboardMarkup(new[]
{
new KeyboardButton("Share my location") {RequestLocation = true},
});
Bot.SendTextMessageAsync(
message.Chat.Id,
"To get the information about weather, you should share your current location.",
replyMarkup: requestLocationKeyboard);
break;
private static async void Bot_OnLocationReceived(object sender, MessageEventArgs e)
{
Thread.Sleep(1000);
var message = e.Message;
if (message == null || message.Type != MessageType.Location) return;
var latitude = message.Location.Latitude;
var longitude = message.Location.Longitude;
latitude = (float)Math.Round(latitude, 3);
longitude = (float)Math.Round(longitude, 3);
Lat = latitude.ToString(CultureInfo.InvariantCulture);
Lon = longitude.ToString(CultureInfo.InvariantCulture);
await Bot.SendTextMessageAsync(
message.Chat.Id,
"_Processing Received Location..._",
ParseMode.Markdown,
replyMarkup: new ReplyKeyboardRemove());
Console.WriteLine("{0};{1}", Lat, Lon);
WeatherResponse weather = GetWeatherData();
await Bot.SendTextMessageAsync(message.Chat.Id, "Your location: " + weather.List[0].Name + "\n" +
"Temperature: " + Convert.ToInt32(weather.List[0].Main.Temp) + " °C" +
"\n" + "Summary: " + weather.List[0].Weather[0].Description);
}