Example #1
2
        public static void GetLang(Update update, string[] args)
        {
            var glangs = Directory.GetFiles(Bot.LanguageDirectory)
                                                        .Select(x => XDocument.Load(x)
                                                                    .Descendants("language")
                                                                    .First()
                                                                    .Attribute("name")
                                                                    .Value
                                                        ).ToList();
            glangs.Insert(0, "All");

            foreach (var lang in glangs)
            {
                var test =
                    $"getlang|-1001049529775|" + lang;
                var count = Encoding.UTF8.GetByteCount(test);
                if (count > 64)
                {
                    Send("Problem with " + lang + ": name is too long!", update.Message.Chat.Id);
                }
            }
            var gbuttons = glangs.Select(x => new InlineKeyboardButton(x, $"getlang|{update.Message.Chat.Id}|{x}")).ToList();
            var baseMenu = new List<InlineKeyboardButton[]>();
            for (var i = 0; i < gbuttons.Count; i++)
            {
                if (gbuttons.Count - 1 == i)
                {
                    baseMenu.Add(new[] { gbuttons[i] });
                }
                else
                    baseMenu.Add(new[] { gbuttons[i], gbuttons[i + 1] });
                i++;
            }

            var gmenu = new InlineKeyboardMarkup(baseMenu.ToArray());
            try
            {
                var result =
                    Bot.Api.SendTextMessage(update.Message.Chat.Id, "Get which language file?",
                        replyToMessageId: update.Message.MessageId, replyMarkup: gmenu).Result;
            }
            catch (AggregateException e)
            {
                foreach (var ex in e.InnerExceptions)
                {
                    var x = ex as ApiRequestException;

                    Send(x.Message, update.Message.Chat.Id);
                }
            }
            catch (ApiRequestException ex)
            {
                Send(ex.Message, update.Message.Chat.Id);
            }
        }
Example #2
0
        public override async Task ExecuteAsync(Update update, Dictionary<string, string> parsedMessage)
        {
            if (_responses.Count == 0)
                await Bot.SendTextMessageAsync(update.Message.Chat.Id, "Зато мы делаем ракеты", false, false, update.Message.MessageId);

            if (!parsedMessage.ContainsKey("message") || string.IsNullOrEmpty(parsedMessage["message"]))
                return;

            var ind = _rng.Next(0, _maxRadnomValue);
            string answer = "";
            for (var i = _weights.Count - 1; i >= 0; i--)
            {
                if (ind >= _weights[i])
                {
                    answer = _responses[i];
                    break;
                }
            }
            // Border case, if the value is between 0 and first answer's weight, no value will be selected
            if (string.IsNullOrEmpty(answer))
            {
                answer = _responses[0];
            }
            await Bot.SendTextMessageAsync(update.Message.Chat.Id, answer, false, false, update.Message.MessageId);
        }
        public IActionResult p([FromBody] Telegram.Bot.Types.Update u)
        {
            list.Add(u);

            switch (u.Type)
            {
            case UpdateType.MessageUpdate:
                var str = $"{DateTime.UtcNow.AddHours(3)}, {u.Message.Type}. {u.Message.From.Id}, {u.Message.From.FirstName} : {u.Message.Text}\n";
                log = str + log;
                SendEmail(str, u.Message.From.Id);
                break;

            case UpdateType.CallbackQueryUpdate:
                str = $"{DateTime.UtcNow.AddHours(3)}, callback. {u.CallbackQuery.From.Id}, {u.CallbackQuery.From.FirstName} : {u.CallbackQuery.Data}\n";
                log = str + log;
                SendEmail(str, u.CallbackQuery.From.Id);
                break;

            case UpdateType.All:
                log = $"{DateTime.UtcNow.AddHours(3)}, {u.Type}\n" + log;
                break;
            }

            Program.HandleUpdate(u);

            return(Ok());
        }
Example #4
0
        public async Task Run()
        {
            var me = await _bot.GetMe();
            
            Log.Logger.Information("{0} is online and fully functional." + Environment.NewLine, me.Username);

            while (IsOnline)
            {
                Update[] updates = new Update[0];
                try
                {
                    updates = await _bot.GetUpdates(Offset);
                }
                catch (Exception ex)
                {
                    Log.Logger.Error("An error has occured while receiving updates. Error message: {0}", ex.Message);
                    ErrorCount++;
                }

                foreach (var update in updates)
                {
                    CommandService.HandleUpdate(update);

                    Offset = update.Id + 1;
                }

                await Task.Delay(1000);
            }
        }
Example #5
0
        public static void Flee(Update update, string[] args)
        {
            var id = update.Message.Chat.Id;
            //check nodes to see if player is in a game
            var node = GetPlayerNode(update.Message.From.Id);
            var game = GetGroupNodeAndGame(update.Message.Chat.Id);
            if (game != null || node != null)
            {
                //try grabbing the game again...
                if (node != null)
                    game =
                        node.Games.FirstOrDefault(
                            x => x.Users.Contains(update.Message.From.Id));
                if (game?.Users.Contains(update.Message.From.Id) ?? false)
                {
                    game?.RemovePlayer(update);

                    return;
                }
                if (node != null)
                {
                    //there is a game, but this player is not in it
                    Send(GetLocaleString("NotPlaying", GetLanguage(id)), id);
                }
            }
            else
            {
                Send(GetLocaleString("NoGame", GetLanguage(id)), id);
            }
        }
Example #6
0
        public override async Task ExecuteAsync(Update update, Dictionary<string, string> parsedMessage)
        {
            // Restore default value
            _location = "Minsk,by";

            // If arguments are supplied, try to insert them into query
            if (parsedMessage.ContainsKey("message"))
            {
                var args = parsedMessage["message"].Split(',');
                if (args.Length >= 2)
                {
                    _location = args[0] + "," + args[1];
                }
            }

            var responseStream = new StreamReader(await GetWeather());
            var weatherContainer = JsonConvert.DeserializeObject<WeatherContainer>(responseStream.ReadToEnd());
            if (weatherContainer.cod == 404)
            {
                await Bot.SendTextMessageAsync(update.Message.Chat.Id, "Invalid arguments.", false, false, update.Message.MessageId);
                return;
            }

            var sb = new StringBuilder();
            sb.Append("Погода в " + weatherContainer.name + ", " + weatherContainer.sys.country);
            sb.AppendLine(" на " + weatherContainer.dt.UnixTimeStampToDateTime().ToLocalTime().ToShortDateString());
            sb.AppendLine();
            sb.AppendLine("Температура: " + weatherContainer.main.temp + " *C, " + weatherContainer.weather[0].description);
            sb.AppendLine("Влажность: " + weatherContainer.main.humidity + "%");
            sb.AppendLine("Ветер: " + weatherContainer.wind.speed + " м/с");
            await Bot.SendTextMessageAsync(update.Message.Chat.Id, sb.ToString(), false, false, update.Message.MessageId);
        }
Example #7
0
        public static void GetLang(Update update, string[] args)
        {
            var glangs = Directory.GetFiles(Bot.LanguageDirectory)
                                                        .Select(x => XDocument.Load(x)
                                                                    .Descendants("language")
                                                                    .First()
                                                                    .Attribute("name")
                                                                    .Value
                                                        ).ToList();
            glangs.Insert(0, "All");

            var gbuttons = glangs.Select(x => new InlineKeyboardButton(x, $"getlang|{update.Message.Chat.Id}|{x}")).ToList();
            var baseMenu = new List<InlineKeyboardButton[]>();
            for (var i = 0; i < gbuttons.Count; i++)
            {
                if (gbuttons.Count - 1 == i)
                {
                    baseMenu.Add(new[] { gbuttons[i] });
                }
                else
                    baseMenu.Add(new[] { gbuttons[i], gbuttons[i + 1] });
                i++;
            }

            var gmenu = new InlineKeyboardMarkup(baseMenu.ToArray());
            Bot.Api.SendTextMessage(update.Message.Chat.Id, "Get which language file?", replyToMessageId: update.Message.MessageId, replyMarkup: gmenu);
        }
Example #8
0
        /// <summary>
        /// Gather all data needed to handle the Update.
        /// </summary>
        public async Task <UpdateDto> Build(Telegram.Bot.Types.Update update)
        {
            if (update == null)
            {
                return(null);
            }

            var parsedChat    = GetParsedChat(update);
            var parsedUser    = GetParsedUser(update);
            var parsedTrackId = await GetParsedTrackId(update);

            var parsedMessage = GetParsedMessage(update);

            var chat = await GetChat(parsedChat?.Id);

            return(new UpdateDto
            {
                ParsedUpdateId = GetParsedUpdateId(update),
                ParsedUpdateType = GetParsedUpdateType(update),
                ParsedBotMessageId = GetParsedBotMessageId(update),
                ParsedChat = parsedChat,
                ParsedUser = parsedUser,
                ParsedTrackId = parsedTrackId,
                ParsedTextMessage = GetParsedTextMessage(update),
                ParsedTextMessageWithLinks = GetParsedTextMessageWithLinks(parsedMessage),
                ParsedData = GetParsedData(update),
                ParsedInlineKeyboard = GetInlineKeyboard(parsedMessage),
                Chat = chat,
                User = await GetUser(parsedUser?.Id),
                AuthorizationToken = await GetAuthorizationToken(parsedUser?.Id),
                Playlist = await GetPlaylist(chat?.PlaylistId),
                Track = await GetTrack(parsedTrackId, chat?.PlaylistId)
            });
        }
Example #9
0
        public override async Task ExecuteAsync(Update update, Dictionary<string, string> parsedMessage)
        {
            var response = await GetHtml();
            string responseString;
            using (var tr = new StreamReader(response))
            {
                responseString = tr.ReadToEnd();
            }

            var startIndex = responseString.IndexOf("+=") + 2;
            var endIndex = responseString.IndexOf(";\ndocument");
            var tempStr = responseString.Substring(startIndex, endIndex - startIndex);
            var partsList = tempStr.Split('+').Select(x => x.Trim()).ToList();
            tempStr = "";
            // remove ' symbols
            partsList.ForEach(x => tempStr += x.Substring(1, x.Length - 2));

            HtmlDocument document = new HtmlDocument();
            document.LoadHtml(tempStr);
            var quote = document.GetElementbyId(QuoteTagId);
            var rating = document.GetElementbyId(RatingTagId);
            
            var result = rating.InnerText + Environment.NewLine + quote.InnerHtml.Replace(QuoteLineBreak, Environment.NewLine);
            
            await Bot.SendTextMessageAsync(update.Message.Chat.Id, HttpUtility.HtmlDecode(result), false, false, update.Message.MessageId);
        }
Example #10
0
        public override async Task ExecuteAsync(Update update, Dictionary<string, string> parsedMessage)
        {
            var rtdRegex = new Regex(@"^(\d*)d(4|6|20|100)");

            if (parsedMessage.ContainsKey("message"))
            {
                if (rtdRegex.IsMatch(parsedMessage["message"]))
                {
                    var rtdMatch = rtdRegex.Match(parsedMessage["message"]);
                    var numberOfDice = rtdMatch.Groups[1].Value == "" ? 1 : int.Parse(rtdMatch.Groups[1].Value);
                    var diceEdges = int.Parse(rtdMatch.Groups[2].Value);
                    if ((numberOfDice > 0 && numberOfDice <= 6) &&
                        (diceEdges == 4 || diceEdges == 6 || diceEdges == 20 || diceEdges == 100))
                    {
                        var sb = new StringBuilder();
                        sb.AppendLine(update.Message.From.FirstName + " rolled the dice.");
                        for (var index = 0; index < numberOfDice; index++)
                        {
                            sb.AppendLine("Dice " + (index + 1) + ": " + (_rng.Next(diceEdges) + 1));
                        }
                        await Bot.SendTextMessageAsync(update.Message.Chat.Id, sb.ToString(), false, false, update.Message.MessageId);
                        return;
                    }
                }
            }

            await Bot.SendTextMessageAsync(update.Message.Chat.Id, "Format: [number(?1-6)]d[number(4|6|20|100)].", false, false, update.Message.MessageId);
        }
Example #11
0
        public async Task<IHttpActionResult> Post(Update update)
        {
            var message = update.Message;

            Console.WriteLine("Received Message from {0}", message.Chat.Id);

            if (message.Type == MessageType.TextMessage)
            {
                // Echo each Message
                await Bot.Api.SendTextMessage(message.Chat.Id, message.Text);
            }
            else if (message.Type == MessageType.PhotoMessage)
            {
                // Download Photo
                var file = await Bot.Api.GetFile(message.Photo.LastOrDefault()?.FileId);

                var filename = file.FileId + "." + file.FilePath.Split('.').Last();

                using (var saveImageStream = File.Open(filename, FileMode.Create))
                {
                    await file.FileStream.CopyToAsync(saveImageStream);
                }

                await Bot.Api.SendTextMessage(message.Chat.Id, "Thx for the Pics");
            }

            return Ok();
        }
Example #12
0
        public async Task Execude(Telegram.Bot.Types.Update update, TelegramBotClient bot)
        {
            var command = update.Message.Text.Split(new char[] { '/', ' ' }, StringSplitOptions.RemoveEmptyEntries);

            if (command.Count() <= 1)
            {
                await bot.SendTextMessageAsync(update.Message.Chat.Id, "Не введен город");

                _log.Information("Не введен город");
                return;
            }
            string city = command[1];

            try
            {
                var weather = _weatherService.Get(city);
                await bot.SendTextMessageAsync(update.Message.Chat.Id, String.Format($"В {weather.City} {weather.Description} и температура {weather.Temperature.ToString("+#;-#;0")} °C"));

                _log.Information(String.Format($"В {weather.City} {weather.Description} и температура {weather.Temperature.ToString("+#;-#;0")} °C"));
            }
            catch (WeatherException ex)
            {
                await bot.SendTextMessageAsync(update.Message.Chat.Id, "Ошибка получения погоды");

                _log.Information("Ошибка получения погоды");
            }
        }
Example #13
0
 public override async Task ExecuteAsync(Update update, Dictionary<string, string> parsedMessage)
 {
     var sb = new StringBuilder();
     sb.AppendLine("Launch time: " + _dwellerBot.LaunchTime.ToUniversalTime());
     sb.AppendLine("Commands processed: " + _dwellerBot.CommandsProcessed);
     sb.AppendLine("Errors: " + _dwellerBot.ErrorCount);
     await Bot.SendTextMessage(update.Message.Chat.Id, sb.ToString(), false, update.Message.MessageId);
 }
Example #14
0
 public async void Execute(Update update)
 {
     var city = GetCityFromMessage(update.Message.Text);
     var weather = _weatherService.GetWeatherForCity(city);
     var message = WeatherMessageBuilder.Build(weather.Name, weather.Description, weather.Temperature);
     await _bot.SendTextMessage(update.Message.Chat.Id, message);
     Console.WriteLine("Echo Message: {0}", message);
 }
Example #15
0
 private static void TratarUpdate(Update update, ref int offset)
 {
     var message = update.Message;
     WriteLine($"Mensagem recebida!");
     WriteLine($"Id: {message.MessageId} | Message type: {message.Type} | Message: {message.Text} | from: {message.Chat.Username}");
     api.SendTextMessage(message.Chat.Id, $"Olá {message.Chat.FirstName}, recebi sua mensagem X)");
     offset = update.Id + 1;
 }
Example #16
0
        public override async Task ExecuteAsync(Update update, Dictionary<string, string> parsedMessage)
        {
            if (!DwellerBot.IsUserOwner(update.Message.From))
                return;

            _dwellerBot.CommandService.SaveCommandStates();

            await Bot.SendTextMessage(update.Message.Chat.Id, "State saved.", false, update.Message.MessageId);
        }
Example #17
0
 public void AddPlayer(Update update)
 {
     var n = Bot.Nodes.FirstOrDefault(x => x.ClientId == NodeId);
     if (n == null) return;
     var g = n.Games.FirstOrDefault(x => x.GroupId == update.Message.Chat.Id);
     g?.Users.Add(update.Message.From.Id);
     var json = JsonConvert.SerializeObject(new PlayerJoinInfo { User = update.Message.From, GroupId = update.Message.Chat.Id });
     n.Broadcast(json);
 }
Example #18
0
 private UpdateType?GetParsedUpdateType(Telegram.Bot.Types.Update update)
 {
     return(update.Type switch
     {
         Telegram.Bot.Types.Enums.UpdateType.Message => UpdateType.Message,
         Telegram.Bot.Types.Enums.UpdateType.InlineQuery => UpdateType.InlineQuery,
         Telegram.Bot.Types.Enums.UpdateType.CallbackQuery => UpdateType.CallbackQuery,
         _ => null,
     });
Example #19
0
        public void RemovePlayer(Update update)
        {
            var n = Bot.Nodes.FirstOrDefault(x => x.ClientId == NodeId);
            if (n == null) return;

            Users.Remove(update.Message.From.Id);
            var json = JsonConvert.SerializeObject(new PlayerFleeInfo { User = update.Message.From, GroupId = update.Message.Chat.Id });
            n.Broadcast(json);
        }
Example #20
0
 public bool IsAppropriate(Update update)
 {
     if (update.Message.Type == MessageType.TextMessage)
     {
         var inputMessage = update.Message.Text;
         return inputMessage.StartsWith("/weather");
     }
     return false;
 }
Example #21
0
 public static void GetStats(Update update, string[] args)
 {
     var reply = $"[Global Stats](werewolf.parawuff.com/Stats)\n";
     if (update.Message.Chat.Type != ChatType.Private)
         reply += $"[Group Stats](werewolf.parawuff.com/Stats/Group/{update.Message.Chat.Id}) ({update.Message.Chat.Title})\n";
     reply += $"[Player Stats](werewolf.parawuff.com/Stats/Player/{update.Message.From.Id}) ({update.Message.From.FirstName})";
     Bot.Api.SendTextMessage(update.Message.Chat.Id, reply, parseMode: ParseMode.Markdown,
         disableWebPagePreview: true);
 }
        public override async Task ExecuteAsync(Update update, Dictionary<string, string> parsedMessage)
        {
            var responseStream = new StreamReader(await GetCurrencyRates());
            var xmlDeserializer = new XmlSerializer(typeof(CurrencyContainerXml.DailyExRates));
            var currencyContainer = new CurrencyContainerXml() { DailyRates = xmlDeserializer.Deserialize(responseStream) as CurrencyContainerXml.DailyExRates };

            // Get data for previous date for comparison
            if (_previousDayCurrencyContainer == null ||
                DateTime.ParseExact(_previousDayCurrencyContainer.DailyRates.Date, "MM/dd/yyyy", null).AddDays(1) !=
                DateTime.ParseExact(currencyContainer.DailyRates.Date, "MM/dd/yyyy", null))
            {
                var ondate = DateTime.ParseExact(currencyContainer.DailyRates.Date, "MM/dd/yyyy", null).AddDays(-1);
                // Rates do not update on weekend (at least here, duh)
                if (ondate.DayOfWeek == DayOfWeek.Sunday)
                {
                    ondate = ondate.AddDays(-2);
                }
                var ondatestring = ondate.ToString(@"MM\/dd\/yyyy");
                responseStream = new StreamReader(await GetCurrencyRates(OnDateParam + ondatestring));
                _previousDayCurrencyContainer = new CurrencyContainerXml() { DailyRates = xmlDeserializer.Deserialize(responseStream) as CurrencyContainerXml.DailyExRates };
            }

            var sb = new StringBuilder();
            sb.Append("Курсы валют на ");
            sb.AppendLine(DateTime.ParseExact(currencyContainer.DailyRates.Date, "MM/dd/yyyy", null).ToShortDateString());
            sb.Append("По отношению к ");
            sb.AppendLine(DateTime.ParseExact(_previousDayCurrencyContainer.DailyRates.Date, "MM/dd/yyyy", null).ToShortDateString());
            sb.AppendLine();

            List<string> currenciesList = new List<string>();
            if (parsedMessage.ContainsKey("message"))
            {
                var names = parsedMessage["message"].Split(',').ToList();
                currenciesList.AddRange(names.Select(cname => cname.ToUpper()));
            }
            if (currenciesList.Count == 0)
                currenciesList = _defaultCurrenciesList;

            foreach (var currency in currencyContainer.DailyRates.Currency.Where(x => currenciesList.Contains(x.CharCode)))
            {
                sb.Append(currency.CharCode + ": " + currency.Rate);
                if (_previousDayCurrencyContainer != null)
                {
                    var diff = currency.Rate -
                               _previousDayCurrencyContainer.DailyRates.Currency.First(
                                   x => x.CharCode == currency.CharCode).Rate;
                    sb.Append(" _(");
                    sb.Append(diff > 0 ? "+" : "-");
                    sb.Append(Math.Abs(diff));
                    sb.Append(")_");
                }
                sb.AppendLine();
            }

            await Bot.SendTextMessage(update.Message.Chat.Id, sb.ToString(), false, update.Message.MessageId, null, true);
        }
Example #23
0
        public override async Task ExecuteAsync(Update update, Dictionary<string, string> parsedMessage)
        {
            // initialize currencies
            if (!_currencies.Any())
            {
                try
                {
                    _currencies = await GetCurrencyList();
                }
                catch(Exception ex)
                {
                    Log.Logger.Error("Unable to get currencies list. Error message: {0}", ex.Message);
                    await Bot.SendTextMessageAsync(update.Message.Chat.Id, "Сервис НБРБ не отвечает на запрос списка валют.", false, false, update.Message.MessageId, null, ParseMode.Markdown);
                    return;
                }
            }
            
            List<string> currenciesList = new List<string>();
            List<string> message = new List<string>();

            if (parsedMessage.ContainsKey("message"))
            {
                message = parsedMessage["message"].Split(' ').Where(s => !string.IsNullOrEmpty(s)).ToList();
                if (message.Contains("to"))
                {
                    if (message.Count != 4)
                    {
                        await Bot.SendTextMessageAsync(update.Message.Chat.Id, "Неверное количество параметров. Формат использования: \"/rate 300 usd to rub\"", false, false, update.Message.MessageId, null, ParseMode.Markdown);
                        return;
                    }

                    int quantity;
                    bool parseResult = int.TryParse(message[0], out quantity);
                    if (!parseResult)
                    {
                        await Bot.SendTextMessageAsync(update.Message.Chat.Id, "Неверно введено количество валюты.", false, false, update.Message.MessageId, null, ParseMode.Markdown);
                        return;
                    }

                    currenciesList.Add(message[1].ToLower());
                    currenciesList.Add(message[3].ToLower());
                    await ConverterRatesCommand(update, currenciesList, quantity);
                }
                else
                {
                    currenciesList = message.Select(s => s.ToLower()).ToList();
                    await RegularRatesCommand(update, currenciesList);
                }
            }
            else
            {
                currenciesList = _defaultCurrenciesList;
                await RegularRatesCommand(update, currenciesList);
            }
        }
Example #24
0
 public static void Update(Update update, string[] args)
 {
     if (update.Message.Date > DateTime.UtcNow.AddSeconds(-3))
     {
         Process.Start(Path.Combine(Bot.RootDirectory, "Resources\\update.exe"));
         Bot.Running = false;
         Program.Running = false;
         Thread.Sleep(500);
         Environment.Exit(1);
     }
 }
        public override void Execute(Api bot, string[] messageParts, Update update)
        {
            string message = string.Empty;
            string[] changedMessageParts = new string[messageParts.Length];

            CorrectMisprintsInWords(messageParts, changedMessageParts);

            message = AnalyzeMessage(changedMessageParts);

            var t = bot.SendTextMessage(update.Message.Chat.Id, message);
            Console.WriteLine("Echo Message: {0}", message);
        }
Example #26
0
 public static void GetRoles(Update update, string[] args)
 {
     if (args.Length > 1)
     {
         var groupName = args.Skip(1).Aggregate((a, b) => a + " " + b).Trim();
         using (var db = new WWContext())
         {
             var roles = db.getRoles(groupName);
             var msg = roles.Aggregate("", (current, r) => current + $"{r.name}: {r.role}\n");
             Bot.Send(msg, update.Message.Chat.Id);
         }
     }
 }
Example #27
0
 internal static bool IsGroupAdmin(Update update)
 {
     //fire off admin request
     try
     {
         var admin = Bot.Api.GetChatMember(update.Message.Chat.Id, update.Message.From.Id).Result;
         return admin.Status == ChatMemberStatus.Administrator || admin.Status == ChatMemberStatus.Creator;
     }
     catch
     {
         return false;
     }
 }
Example #28
0
 public static void PlayTime(Update update, string[] args)
 {
     if (args.Length > 1)
     {
         var playerCount = int.Parse(args[1]);
         using (var db = new WWContext())
         {
             var counts = db.getPlayTime(playerCount).First();
             var msg =
                 $"(In minutes)\nMin: {counts.Minimum}\nMax: {counts.Maximum}\nAverage: {counts.Average}";
             Bot.Send(msg, update.Message.Chat.Id);
         }
     }
 }
Example #29
0
 public override async Task ExecuteAsync(Update update, Dictionary<string, string> parsedMessage)
 {
     var responseStream = new StreamReader(await GetCurrencyRates());
     var currencyContainer = JsonConvert.DeserializeObject<CurrencyContainer>(responseStream.ReadToEnd());
     var sb = new StringBuilder();
     sb.Append("Курсы валют на ");
     sb.AppendLine(currencyContainer.query.created.ToShortDateString());
     sb.AppendLine();
     foreach (var currency in currencyContainer.query.results.rate)
     {
         sb.AppendLine(currency.Name.Substring(0, 3) + ": " + currency.Rate.Substring(0, currency.Rate.Length - 2));
     }
     await Bot.SendTextMessageAsync(update.Message.Chat.Id, sb.ToString(), false, false, update.Message.MessageId);
 }
Example #30
0
        public async void Execute(Update update)
        {
            var inputMessage = update.Message.Text;
            var messageParts = inputMessage.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            var city = messageParts.Length == 1 ? "Minsk" : messageParts.Skip(1).First();
            WebUtility.UrlEncode(city);

            var weather = service.GetWeather(city);

            var message = "In " + weather.Name + " " + weather.Description + " and the temperature is " + TemperatureProvider.ConvertToCelsiusDegree(weather.Temperature);

            var t = await bot.SendTextMessage(update.Message.Chat.Id, message);
            Console.WriteLine("Echo Message: {0}", message);
            
        }
        public void Execute(Api bot, string[] currencies, Update update)
        {
            string url = string.Format(@"https://query.yahooapis.com/v1/public/yql?q=env 'store://datatables.org/alltableswithkeys'; select * from yahoo.finance.xchange where pair='{0}'&format=json", currencies[1] + currencies[2]);

            string responseString = new ResponseService().GetResponse(url);

            Console.WriteLine(responseString);

            var rateResponse = JsonConvert.DeserializeObject<RateResponse>(responseString);

            var message = "1 " + currencies[1] + " = " + rateResponse.query.results.rate.Rate + currencies[2];

            var t = bot.SendTextMessage(update.Message.Chat.Id, message);
            Console.WriteLine("Echo Message: {0}", message);
        }
Example #32
0
        public override async Task ExecuteAsync(Update update, Dictionary<string, string> parsedMessage)
        {
            if (!DwellerBot.IsUserOwner(update.Message.From))
                return;

	        ICommand command;
	        if (_dwellerBot.CommandService.RegisteredCommands.TryGetValue("/savestate", out command))
	        {
		        await command.ExecuteAsync(update, parsedMessage);
            }

            _dwellerBot.IsOnline = false;

            await Bot.SendTextMessage(update.Message.Chat.Id, "Shutting down.", false, update.Message.MessageId);
            await Bot.GetUpdates(update.Id + 1);
        }
Example #33
0
        public static void GetIdles(Update update, string[] args)
        {
            //check user ids and such
            List<int> ids = new List<int>();
            foreach (var arg in args.Skip(1).FirstOrDefault()?.Split(' ')??new [] {""})
            {
                var id = 0;
                if (int.TryParse(arg, out id))
                {
                    ids.Add(id);
                }
            }

            //now check for mentions
            foreach (var ent in update.Message.Entities.Where(x => x.Type == MessageEntityType.TextMention))
            {
                ids.Add(ent.User.Id);
            }

            //check for reply
            if (update.Message.ReplyToMessage != null)
                ids.Add(update.Message.ReplyToMessage.From.Id);

            var reply = "";
            //now get the idle kills
            using (var db = new WWContext())
            {
                foreach (var id in ids)
                {
                    var idles = db.GetIdleKills24Hours(id).FirstOrDefault() ?? 0;
                    //get the user
                    ChatMember user = null;
                    try
                    {
                        user = Bot.Api.GetChatMember(update.Message.Chat.Id, id).Result;
                    }
                    catch
                    {
                        // ignored
                    }

                    reply += $"{id} ({user?.User.FirstName}) has been idle killed {idles} time(s) in the past 24 hours\n";
                }
            }

            Send(reply, update.Message.Chat.Id);
        }
Example #34
0
        public static void NextGame(Update update, string[] args)
        {
            var id = update.Message.Chat.Id;
            using (var db = new WWContext())
            {
                var grp = db.Groups.FirstOrDefault(x => x.GroupId == id);
                if (grp == null)
                {
                    grp = MakeDefaultGroup(id, update.Message.Chat.Title, "nextgame");
                    db.Groups.Add(grp);
                    db.SaveChanges();
                }

                //check nodes to see if player is in a game
                //node = GetPlayerNode(update.Message.From.Id);
                var game = GetGroupNodeAndGame(update.Message.Chat.Id);
                if (game != null)
                {

                    if (game?.Users.Contains(update.Message.From.Id) ?? false)
                    {
                        if (game?.GroupId != update.Message.Chat.Id)
                        {
                            //player is already in a game, and alive
                            Send(
                                GetLocaleString("AlreadyInGame", grp.Language ?? "English",
                                    game.ChatGroup), update.Message.Chat.Id);
                            return;
                        }
                    }
                }

                if (db.NotifyGames.Any(x => x.GroupId == id && x.UserId == update.Message.From.Id))
                {
                    Send(GetLocaleString("AlreadyOnWaitList", grp.Language, grp.Name),
                        update.Message.From.Id);
                }
                else
                {
                    db.Database.ExecuteSqlCommand(
                        $"INSERT INTO NotifyGame VALUES ({update.Message.From.Id}, {id})");
                    db.SaveChanges();
                    Send(GetLocaleString("AddedToWaitList", grp.Language, grp.Name),
                        update.Message.From.Id);
                }
            }
        }
Example #35
0
        public void Update([FromRoute] string token, [FromBody] Telegram.Bot.Types.Update update)
        {
            try
            {
                var accessToken = _configuration["Settings:accessToken"];
                if (token != accessToken)
                {
                    return;
                }

                if (update == null)
                {
                    return;
                }

                if (update.Type == Telegram.Bot.Types.Enums.UpdateType.CallbackQuery)
                {
                    if (update.CallbackQuery != null && !string.IsNullOrEmpty(update.CallbackQuery.Data) &&
                        update.CallbackQuery.Message != null && !string.IsNullOrEmpty(update.CallbackQuery.Message.Text))
                    {
                        ProcessCallbackQuery(update);
                    }
                }
                else if (update.Type == Telegram.Bot.Types.Enums.UpdateType.Message)
                {
                    if (update.Message != null && !string.IsNullOrEmpty(update.Message.Text))
                    {
                        ProcessMessage(update);
                    }
                }
            }
            catch (Exception e)
            {
                _bot.SendTextMessageAsync(update.Message.Chat.Id,
                                          $"Exception: {e.ToString()}");
                //throw;
            }
        }
Example #36
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, TelegramBotClient client)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            var routeBuilder = new RouteBuilder(app);

            routeBuilder.MapPost("api/update", async context => {
                StreamReader sr = new StreamReader(context.Request.Body);
                string body     = await sr.ReadToEndAsync();
                Telegram.Bot.Types.Update update = JsonConvert.DeserializeObject <Telegram.Bot.Types.Update>(body);

                switch (update.Type)
                {
                case UpdateType.Message:
                    await client.SendTextMessageAsync(update.Message.Chat.Id,
                                                      "Просто ответ на сообщение", replyToMessageId: update.Message.MessageId);
                    break;

                case UpdateType.EditedMessage:
                    await client.SendTextMessageAsync(update.EditedMessage.Chat.Id,
                                                      "Ответ на отредактированное сообщение",
                                                      replyToMessageId: update.EditedMessage.MessageId);
                    break;
                }
            });

            app.UseRouter(routeBuilder.Build());

            app.Run(async context => {
                var me = await client.GetMeAsync();

                context.Response.ContentType = "text/html; charset=utf-8";
                await context.Response.WriteAsync($"<h1>My name is {me.FirstName}</h1>");
            });
        }
        //public string GetData(int value)
        //{
        //    return string.Format("You entered: {0}", value);
        //}

        //public CompositeType GetDataUsingDataContract(CompositeType composite)
        //{
        //    if (composite == null)
        //    {
        //        throw new ArgumentNullException("composite");
        //    }
        //    if (composite.BoolValue)
        //    {
        //        composite.StringValue += "Suffix";
        //    }
        //    return composite;
        //}

        public void GetUpdate(Telegram.Bot.Types.Update update)
        {
            log.InfoFormat("{0}:{1}", update.Message.From.Username, update.Message.Text);

            var Bot = new Telegram.Bot.TelegramBotClient(ConfigurationManager.AppSettings["telegramToken"]);

            if (update.Message.Text != null)
            {
                switch (update.Message.Text.ToLower())
                {
                case "привет":
                    Bot.SendTextMessageAsync(update.Message.Chat.Id, "Привет," + update.Message.From.FirstName);
                    break;

                case "/newgame":
                    InlineKeyboardMarkup inlineKeyboardMarkup = new InlineKeyboardMarkup(
                        new Telegram.Bot.Types.InlineKeyboardButtons.InlineKeyboardButton[]
                    {
                        new Telegram.Bot.Types.InlineKeyboardButtons.InlineKeyboardCallbackButton("4", "1"),
                        new Telegram.Bot.Types.InlineKeyboardButtons.InlineKeyboardCallbackButton("4", "2"),
                        new Telegram.Bot.Types.InlineKeyboardButtons.InlineKeyboardCallbackButton("4", "3"),
                        new Telegram.Bot.Types.InlineKeyboardButtons.InlineKeyboardCallbackButton("4", "4"),
                        new Telegram.Bot.Types.InlineKeyboardButtons.InlineKeyboardCallbackButton("4", "5"),
                        new Telegram.Bot.Types.InlineKeyboardButtons.InlineKeyboardCallbackButton("4", "6")
                    });



                    //Telegram.Bot.Types.Update x;                        x.
                    //ReplyKeyboardMarkup replyKeyboardMarkup =
                    //    new ReplyKeyboardMarkup(
                    //        new[]
                    //        {
                    //            new Telegram.Bot.Types.KeyboardButton("1"),
                    //            new Telegram.Bot.Types.KeyboardButton("2"),
                    //            new Telegram.Bot.Types.KeyboardButton("3"),
                    //            new Telegram.Bot.Types.KeyboardButton("4"),
                    //            new Telegram.Bot.Types.KeyboardButton("5"),
                    //            new Telegram.Bot.Types.KeyboardButton("6")
                    //        });

                    Bot.SendTextMessageAsync(update.Message.Chat.Id, "————————————————", Telegram.Bot.Types.Enums.ParseMode.Markdown, true, true, 0, inlineKeyboardMarkup);

                    break;

                case "гад":
                case "гандон":
                case "гнида":
                case "гавно":
                case "говнище":
                case "говно":
                case "говнюк":
                case "гондон":
                case "дерьмо":
                case "долбоеб":
                case "долбоёб":
                case "ебан":
                case "ебанат":
                case "ебанашка":
                case "ебанутый":
                case "ёбнутый":
                case "жлоб":
                case "жопа":
                case "жопошник":
                case "заебал":
                case "засранец":
                case "идиот":
                case "мудак":
                case "мудозвон":
                case "негодяй":
                case "обмудок":
                case "падла":
                case "педик":
                case "педрила":
                case "петушара":
                case "пидор":
                case "пидорас":
                case "пидрила":
                case "поебень":
                case "сучара":
                case "сучка":
                case "ублюдок":
                case "уёба":
                case "уёбок":
                case "хуесос":
                case "хуила":
                case "чмо":
                case "чмошник":
                    Bot.SendTextMessageAsync(update.Message.Chat.Id, "Пошёл нахуй, " + update.Message.From.FirstName);
                    break;



                default:
                    break;
                }
            }
        }