• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# Types.Update类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中Telegram.Bot.Types.Update的典型用法代码示例。如果您正苦于以下问题:C# Update类的具体用法?C# Update怎么用?C# Update使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



Update类属于Telegram.Bot.Types命名空间,在下文中一共展示了Update类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: ExecuteAsync

        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);
        }
开发者ID:Angelore,项目名称:dwellerbot,代码行数:25,代码来源:AskStasonCommand.cs


示例2: ExecuteAsync

        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);
        }
开发者ID:Angelore,项目名称:dwellerbot,代码行数:32,代码来源:WeatherCommand.cs


示例3: Run

        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);
            }
        }
开发者ID:forcewake,项目名称:dwellerbot,代码行数:29,代码来源:DwellerBot.cs


示例4: ExecuteAsync

        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);
        }
开发者ID:Angelore,项目名称:dwellerbot,代码行数:26,代码来源:BashimCommand.cs


示例5: GetLang

        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);
        }
开发者ID:RainRat,项目名称:Werewolf,代码行数:27,代码来源:GeneralCommands.cs


示例6: ExecuteAsync

        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);
        }
开发者ID:Angelore,项目名称:dwellerbot,代码行数:28,代码来源:RtdCommand.cs


示例7: Post

        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();
        }
开发者ID:johnvan7,项目名称:telegram.bot,代码行数:28,代码来源:Program.cs


示例8: Flee

        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);
            }
        }
开发者ID:CloneMMDDCVII,项目名称:Werewolf,代码行数:30,代码来源:GameCommands.cs


示例9: Execute

 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);
 }
开发者ID:olegpopok,项目名称:BecomeSolid,代码行数:8,代码来源:WeatherCommand.cs


示例10: ExecuteAsync

 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);
 }
开发者ID:forcewake,项目名称:dwellerbot,代码行数:8,代码来源:DebugCommand.cs


示例11: TratarUpdate

 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;
 }
开发者ID:JoelRamosM,项目名称:BotRegPonto,代码行数:8,代码来源:Program.cs


示例12: AddPlayer

 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);
 }
开发者ID:RainRat,项目名称:Werewolf,代码行数:9,代码来源:GameInfo.cs


示例13: GetStats

 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);
 }
开发者ID:RainRat,项目名称:Werewolf,代码行数:9,代码来源:GeneralCommands.cs


示例14: IsAppropriate

 public bool IsAppropriate(Update update)
 {
     if (update.Message.Type == MessageType.TextMessage)
     {
         var inputMessage = update.Message.Text;
         return inputMessage.StartsWith("/weather");
     }
     return false;
 }
开发者ID:eugeni96,项目名称:SOLID,代码行数:9,代码来源:WeatherCommand.cs


示例15: RemovePlayer

        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);
        }
开发者ID:RainRat,项目名称:Werewolf,代码行数:9,代码来源:GameInfo.cs


示例16: ExecuteAsync

        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);
        }
开发者ID:forcewake,项目名称:dwellerbot,代码行数:9,代码来源:SaveStateCommand.cs


示例17: ExecuteAsync

        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);
        }
开发者ID:AlexanderChechet,项目名称:BecomeSOLID,代码行数:56,代码来源:RateNbrbCommand.cs


示例18: ExecuteAsync

        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);
            }
        }
开发者ID:Angelore,项目名称:dwellerbot,代码行数:55,代码来源:RateNbrbCommand.cs


示例19: GetLang

        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);
            }
        }
开发者ID:RaptDept,项目名称:Werewolf,代码行数:55,代码来源:GeneralCommands.cs


示例20: Update

 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);
     }
 }
开发者ID:RainRat,项目名称:Werewolf,代码行数:11,代码来源:DevCommands.cs



注:本文中的Telegram.Bot.Types.Update类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Expressions.MethodInvocationExpression类代码示例发布时间:2022-05-26
下一篇:
C# Kauwa.SessionException类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap