Exemplo n.º 1
1
        static async Task GetUpdate()
        {
            TelegramBotClient bot = new TelegramBotClient(TOKEN);
            int offset            = 0;

            try
            {
                await bot.SetWebhookAsync("");

                while (true)
                {
                    var updates = await bot.GetUpdatesAsync(offset, 1);

                    foreach (var update in updates)
                    {
                        var message = update.Message;
                        if (message != null)
                        {
                            if (message.Text == "Hello!")
                            {
                                Console.WriteLine("Сообщение: " + message.Text);

                                await bot.SendTextMessageAsync(message.Chat.Id, "Hello World!");
                            }


                            if (message.Text == "Муги, скинь фоточку" || message.Text == "Муги, скинь фоточку.")
                            {
                                Random rand = new Random();

                                string[] pictures = { "https://coubsecure-s.akamaihd.net/get/b173/p/coub/simple/cw_timeline_pic/708ec3a3fcf/d37c5efc2377c8301300a/big_1497962224_image.jpg",
                                                      "https://i.ytimg.com/vi/-JWN1W5zSHQ/maxresdefault.jpg",
                                                      "https://i.imgur.com/Lpxh2Ew.jpg",
                                                      "https://static1.fjcdn.com/comments/Mugi+is+best+kon+_e62d3e424899cd5b5f93269d912cb2a8.jpg",
                                                      "http://imgur.com/cdte1Sq.jpg",
                                                      "https://i.ytimg.com/vi/lgSch646X6M/hqdefault.jpg",
                                                      "https://i.pinimg.com/236x/a6/38/5d/a6385d1c56a793e9677d14cca594bf89--mugi-k-on-k-on-mugi.jpg?b=t" };

                                await bot.SendPhotoAsync(message.Chat.Id, pictures[rand.Next(7)]);
                            }

                            if (message.Text == "Муги, кинь кубик." || message.Text == "Муги, кинь кубик")
                            {
                                Random rand = new Random();

                                string msg = String.Format("Кинула! \nНа кубике выпало {0}.", rand.Next(20) + 1);
                                await bot.SendTextMessageAsync(message.Chat.Id, msg);
                            }


                            if (message.Text != null)
                            {
                                Regex regex = new Regex(@"Муги, кинь \d+d\d+");

                                MatchCollection matches = regex.Matches(message.Text);
                                if (matches.Count > 0)
                                {
                                    Random rand = new Random();

                                    int modifier = 0;
                                    int quantity = Int32.Parse(Regex.Match(message.Text, @"\d+").Value);

                                    string sizeS = Regex.Match(message.Text, @"d(\d+)").Value;
                                    int    size  = Int32.Parse(Regex.Replace(sizeS, @"d", ""));

                                    Regex regexM = new Regex(@"\+(\d+)");

                                    MatchCollection matchesM = regexM.Matches(message.Text);

                                    if (matchesM.Count > 0)
                                    {
                                        string modifierS = Regex.Match(message.Text, @"\+(\d+)").Value;
                                        modifier = Int32.Parse(Regex.Replace(modifierS, @"\+", ""));
                                    }

                                    Console.WriteLine("Числа: " + quantity + " " + size);

                                    int number = 0;
                                    for (int i = 0; i < quantity; i++)
                                    {
                                        int rands = rand.Next(size) + 1;
                                        number += rands;
                                        //Console.WriteLine("Кубик: " + rands);
                                    }
                                    number += modifier;

                                    string msg = String.Format("Кинула! \nВыпало {0}.", number);
                                    await bot.SendTextMessageAsync(message.Chat.Id, msg);
                                }
                            }

                            if (message.Text != null)
                            {
                                Regex           regex   = new Regex(@"Иг.рь(\w*)");
                                MatchCollection matches = regex.Matches(message.Text);
                                if (matches.Count > 0)
                                {
                                    Console.Beep();
                                    Console.Beep();
                                    Console.Beep();
                                    Console.WriteLine("Тебя зовут: " + message.Text);
                                }
                            }

                            offset = update.Id + 1;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Ошибочка: " + e);
                //offset = update.Id + 1;
            }
        }
Exemplo n.º 2
0
 public void Initialize()
 {
     client = new TelegramBotClient()
     {
         Token = ""
     };
 }
Exemplo n.º 3
0
 public Bot(string name, string token)
 {
     Configuration = new BotConfiguration();
     Token = token;
     Client = new TelegramBotClient() { Token = token };
     Data = new BotData(this);
     Name = name;
 }
Exemplo n.º 4
0
 public EndCommand(TelegramBotClient botClient, long chatId)
 {
     _botClient = botClient;
     _chatId    = chatId;
 }
Exemplo n.º 5
0
        private void Process()
        {
            Console.OutputEncoding = Encoding.UTF8;

            var bot_token    = Environment.GetEnvironmentVariable("bot_token");
            var gitlab_token = Environment.GetEnvironmentVariable("gitlab_token");
            var team         = Environment.GetEnvironmentVariable("team");
            var gitlab_url   = Environment.GetEnvironmentVariable("GITLAB_HOST");

            TelegramBotClient Bot = new TelegramBotClient(bot_token);


            var client = new RestClient($"{gitlab_url}/api/v4/")
            {
                Authenticator = new JwtAuthenticator(gitlab_token)
            };

            var users = team.Split(';');


            MergeRequest[] getMRs(string userId)
            {
                var request = new RestRequest($"merge_requests?state=opened&scope=all&per_page=100&author_username={userId}", DataFormat.Json);

                var response = client.Get(request);


                return(JsonConvert.DeserializeObject <MergeRequest[]>(response.Content));
            }

            var mergeRequests = new List <MergeRequest>();

            Array.ForEach(users, user =>
            {
                mergeRequests.AddRange(getMRs(user.ToLower()));
            });

            var sr = new StringBuilder();

            // Сгруппировать МРы по автору
            mergeRequests.GroupBy(mr => mr.Author.Name).
            Select(group => new { name = group.Key, mrs = group.ToList() }).
            ToList().ForEach(group =>
            {
                sr.AppendLine("");
                sr.AppendLine($"*{group.name}*");

                group.mrs.ForEach(mr =>
                {
                    sr.AppendLine("");
                    sr.AppendLine($"*Название:*             {mr.Title}");
                    sr.AppendLine($"*Когда обновлялся:*     {mr.UpdatedAt.ToString("dd-MM-yyyy")}");
                    sr.AppendLine($"*Дней с обновления:*    {(int)(DateTime.Now - mr.UpdatedAt).TotalDays}");
                    sr.AppendLine($"*WIP:*                  {mr.WorkInProgress}");
                    sr.AppendLine($"*Проект:*               {(mr.ProjectId == 452 ? "AKIT" : "ASSR")}");
                    sr.AppendLine($"*Конфликты:*            {mr.HasConflicts}");
                    sr.AppendLine($"[ссылка]({mr.WebUrl})");
                });
            });

            Bot.SendTextMessageAsync("-345821829", sr.ToString(), parseMode: ParseMode.Markdown).Wait();

            Console.WriteLine(sr.ToString());
        }
 public async Task ExecuteAsync(Message message, TelegramBotClient botClient)
 {
     await botClient.SendPictureFromBytesAsync(message.Chat.Id, await generator.GetBytes());
 }
 public void Setup()
 {
     _botClient            = new TelegramBotClient(ApiKey);
     _botClient.OnMessage += BotClientOnMessage;
     _botClient.StartReceiving();
 }
Exemplo n.º 8
0
        public async void StartListen()
        {
            var bot = new TelegramBotClient("1794355084:AAFlARMlsA6HlVpX1IXELAOdTxjWCrYgCWE");
            await bot.SetWebhookAsync("");

            try
            {
                photo = new FileToSend(
                    "https://sun9-46.userapi.com/impg/yP7m1fjPEW27EEPT0ZC5MBCmErrYcEMNKeYBGw/KY22S9UjkNw.jpg?size=1036x588&quality=96&sign=679220da15c5f3bf9ac1c7de9b26453b&type=album");

                bot.OnMessage += async(object sender, Telegram.Bot.Args.MessageEventArgs e) =>
                {
                    try
                    {
                        string message = e.Message.Text;

                        if (message == "/start")
                        {
                            Logger.Input("Hello world");

                            using (DatabaseContext db = new DatabaseContext())
                            {
                                List <DSTUSaved> saved = db.Saved.ToList();

                                saved = saved.OrderBy(p => p.SortId).ToList();

                                await bot.SendPhotoAsync(e.Message.Chat.Id, photo,
                                                         "Ректор рекомендует!\nСтуденту от студентов! В 2021 году Студенческий совет разработал для тебя полезного бота! Мы выяснили, что необходимо студенту, чтобы комфортно адаптироваться в университете.Мы рады предложить тебе навигатор, который поможет в первые дни учебы)",
                                                         false, 0, createKeyboardMenu(saved, false));
                            }

                            return;
                        }

                        if (message == "Назад")
                        {
                            using (DatabaseContext db = new DatabaseContext())
                            {
                                List <DSTUSaved> saved = db.Saved.ToList();

                                saved = saved.OrderBy(p => p.SortId).ToList();

                                await bot.SendPhotoAsync(e.Message.Chat.Id, photo,
                                                         "Ректор рекомендует!\nСтуденту от студентов! В 2021 году Студенческий совет разработал для тебя полезного бота! Мы выяснили, что необходимо студенту, чтобы комфортно адаптироваться в университете.Мы рады предложить тебе навигатор, который поможет в первые дни учебы)",
                                                         false, 0, createKeyboardMenu(saved, false));
                            }
                        }

                        using (DatabaseContext db = new DatabaseContext())
                        {
                            List <DSTUSaved> ar = db.Saved.ToList();
                            ar = ar.OrderBy(p => p.SortId).ToList();

                            foreach (var item in ar)
                            {
                                if (item.Action == message)
                                {
                                    if (item.SubActions == "null")
                                    {
                                        await bot.SendTextMessageAsync(e.Message.Chat.Id, item.OptionsJson, ParseMode.Default, false, false);
                                    }
                                    else
                                    {
                                        await bot.SendTextMessageAsync(e.Message.Chat.Id, item.OptionsJson, ParseMode.Default, false, false, 0, createSubMenu(JsonConvert.DeserializeObject <Dictionary <string, string> >(item.SubActions), true));
                                    }
                                    await bot.DeleteMessageAsync(e.Message.Chat.Id, e.Message.MessageId);

                                    return;
                                }

                                if (item.SubActions != "null")
                                {
                                    Dictionary <string, string> subActions = JsonConvert.DeserializeObject <Dictionary <string, string> >(item.SubActions);

                                    if (subActions.ContainsKey(message))
                                    {
                                        await bot.SendTextMessageAsync(e.Message.Chat.Id, subActions[message]);

                                        await bot.DeleteMessageAsync(e.Message.Chat.Id, e.Message.MessageId);
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        await bot.SendTextMessageAsync(e.Message.Chat.Id, ex.Message);
                    }
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            bot.StartReceiving();

            while (true)
            {
            }
        }
Exemplo n.º 9
0
        static void Main(string[] args)
        {
            if (args.Length < 2)
            {
                //Notify user about input error and offer help
                Console.WriteLine($"Not enough parameters specified.");
                Console.WriteLine(helpText);
                Environment.Exit(1);
            }
            else
            {
                botClient = new TelegramBotClient(botToken);
                Console.WriteLine($"Bot selftest result was {(botClient.TestApiAsync().Result ? "successful" : "unsuccessful")}");

                string mode = args[0];
                switch (mode.ToLower())
                {
                    #region Start Command
                case "start":
                    if (File.Exists(sessionLocation))
                    {
                        //Read existing session
                        if (WorkSession.TryParse(sessionLocation, out WorkSession oldSession))
                        {
                            Console.WriteLine("You already have a session running.");
                            Console.WriteLine($"It was started on {new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc).AddSeconds(oldSession.StartTime).ToString()} with subject \"{oldSession.Subject}\"");
                        }
                        else
                        {
                            Console.WriteLine("You have a session of an unsupported format running.");
                        }

                        //Selection text
                        string selectionText = $"[D]iscard previous session{(oldSession != null ? " | [C]ontinue previous session" : string.Empty)}";
                        Console.WriteLine(selectionText);
                        while (true)
                        {
                            ConsoleKeyInfo key = Console.ReadKey();
                            if (key.Key == ConsoleKey.D)
                            {
                                File.Delete(sessionLocation);
                                StartAndSaveSession(args[1]);
                                break;
                            }
                            else if (key.Key == ConsoleKey.C && oldSession != null)
                            {
                                break;
                            }
                            else
                            {
                                Console.WriteLine("You've made an invalid selection.");
                                Console.WriteLine("selectionText");
                            }
                        }
                    }
                    else
                    {
                        StartAndSaveSession(args[1]);
                    }

                    break;

                    #endregion
                    #region Stop Command
                case "stop":
                    if (File.Exists(sessionLocation))
                    {
                        //Read information about the current session
                        if (WorkSession.TryParse(sessionLocation, out WorkSession session))
                        {
                            //Finalize session with the user-provided summary
                            Console.WriteLine($"Finishing current session titled \"{session.Subject}\".");
                            if (session.FinishSession(args[1]))
                            {
                                TimeSpan span = TimeSpan.FromSeconds(session.Duration);
                                //Notify Telegram
                                Console.WriteLine($"Pushing update to Telegram");
                                botClient.SendTextMessageAsync(new Telegram.Bot.Types.ChatId(botChatId), $"User *{Environment.UserName}* has stopped working on *{session.Subject}*\n\n*Summary*\n`{session.Summary}`\n\n*Total time spent*\n`{span.Days} Days {span.Hours} Hours {span.Minutes} Minutes {span.Seconds} Seconds`", Telegram.Bot.Types.Enums.ParseMode.Markdown);
                                Console.WriteLine($"Deleting session information from disk.");
                                File.Delete(sessionLocation);
                            }
                            else
                            {
                                Console.WriteLine($"Your current session could not be terminated.");
                                Environment.Exit(1);
                            }
                        }
                        else
                        {
                            Console.WriteLine($"A session using an unsupported file-format was found. Make sure you are using a correct version.");
                            Environment.Exit(1);
                        }
                    }
                    else
                    {
                        Console.WriteLine("You're currently not working on a time-tracked session.");
                        Environment.Exit(1);
                    }

                    break;

                    #endregion
                    #region Status Command
                case "status":
                    //Check if we are tracking time
                    if (File.Exists(sessionLocation))
                    {
                        //Read information about the current session
                        if (WorkSession.TryParse(sessionLocation, out WorkSession session))
                        {
                            Console.WriteLine($"Updating status of session \"{session.Subject}\"");
                            //Fetch current time to calculate a difference & send it off to Telegram
                            if (TimeData.FetchTimeData(out TimeData data))
                            {
                                int      duration = data.unixtime - session.StartTime;
                                TimeSpan span     = TimeSpan.FromSeconds(duration);

                                //Notify the Telegram group
                                Console.WriteLine($"Pushing update to Telegram");
                                botClient.SendTextMessageAsync(
                                    new Telegram.Bot.Types.ChatId(botChatId),
                                    $"User *{Environment.UserName}* has issued an update on *{session.Subject}*\n\n*Details*\n`{args[1]}`\n\n*Time spent so far*\n`{span.Days} Days {span.Hours} Hours {span.Minutes} Minutes {span.Seconds} Seconds`",
                                    Telegram.Bot.Types.Enums.ParseMode.Markdown
                                    );
                            }
                        }
                    }
                    else
                    {
                        //Notify about user error
                        Console.WriteLine("You're currently not working on a time-tracked session.");
                    }

                    break;

                    #endregion
                    #region Invalid Command
                default:
                    //Notify about user error & offer help
                    Console.WriteLine("Invalid mode specified.");
                    Console.WriteLine(helpText);
                    break;
                    #endregion
                }
            }
        }
        public async static Task <User> GetMe(string Token)
        {
            TelegramBotClient botClient = new TelegramBotClient(Token);

            return(await botClient.GetMeAsync());
        }
 /// <summary>
 /// Initializes a new Bot
 /// </summary>
 /// <param name="botOptions">Options used to configure the bot</param>
 protected BotBase(IOptions <BotOptions <TBot> > botOptions)
 {
     BotOptions = botOptions.Value;
     Client     = new TelegramBotClient(BotOptions.ApiToken);
 }
Exemplo n.º 12
0
 public abstract void Execute(Message message, TelegramBotClient client);
Exemplo n.º 13
0
        public MedocTelegram()
        {
            botToken = SessionStorage.inside.TelegramToken;

            string tokenStr = ParsedArgs.GetArgument("telegramtoken");

            if (tokenStr.Length > 0)
            {
                botToken = tokenStr;
                Log.Write("MedocTelegram: Token was forcibly set to " + tokenStr.Substring(0, 3) + "...");                 // Print only first 3 symbols - just to make sure
            }

            try
            {
                botClient = new TelegramBotClient(botToken);
                Log.Write(LogLevel.NORMAL, "MedocTelegram: Created TelegramBotClient object");
            }
            catch (Exception ex)
            {
                Log.Write("MedocTelegram: Cannot create TelegramBotClient object\r\n" + ex.Message);
                return;
            }

            //Console.WriteLine(botClient.GetMeAsync().Result.Username);

            botClient.OnCallbackQuery       += OnCallbackQueryReceived;
            botClient.OnInlineQuery         += BotClient_OnInlineQuery;
            botClient.OnInlineResultChosen  += BotClient_OnInlineResultChosen;
            botClient.OnMessage             += OnMessageReceived;
            botClient.OnReceiveError        += BotClient_OnReceiveError;
            botClient.OnReceiveGeneralError += BotClient_OnReceiveGeneralError;

            try
            {
                Log.Write(LogLevel.NORMAL, "MedocTelegram: Client begins to receive updates...");

                /* Not needed
                 *      UpdateType[] updates = new UpdateType [4]{
                 *              UpdateType.CallbackQuery,
                 *              UpdateType.InlineQuery,
                 *              UpdateType.ChosenInlineResult,
                 *              UpdateType.Message
                 *      };
                 */



                botClient.StartReceiving(/*updates*/);                 // Start loop
            }
            catch (Exception ex)
            {
                Log.Write(LogLevel.NORMAL, "MedocTelegram: Cannot start receiving updates\r\n" + ex.Message);
                return;
            }

            if (TelegramChatsStorage.TelegramChats == null)             // May be rare
            {
                Log.Write(LogLevel.EXPERT, "MedocTelegram: Internal chat list is null");
                return;
            }
        }
Exemplo n.º 14
0
 public double GetScore(Message message, TelegramBotClient botClient)
 => message.GetMatch("hello", "привет", "hi", "hey", "хей", "хай");
Exemplo n.º 15
0
        private static async Task StartBotsAsync(bool advancedModeDebugDisguised)
        {
            GlobalVariables.Bots = new Dictionary <long, TelegramBotAbstract>();
            if (_botInfos != null && advancedModeDebugDisguised == false)
            {
                foreach (var bot in _botInfos)
                {
                    var botClient = new TelegramBotClient(bot.GetToken());
                    GlobalVariables.Bots[botClient.BotId] =
                        new TelegramBotAbstract(botClient, bot.GetWebsite(), bot.GetContactString(),
                                                BotTypeApi.REAL_BOT);
                    if (!bot.AcceptsMessages())
                    {
                        continue;
                    }

                    var onmessageMethod = bot.GetOnMessage();
                    if (onmessageMethod == null)
                    {
                        continue;
                    }

                    botClient.OnMessage += onmessageMethod;
                    botClient.StartReceiving();
                }
            }

            if (_userBotsInfos != null && advancedModeDebugDisguised == false)
            {
                foreach (var userbot in _userBotsInfos)
                {
                    var client = await UserbotConnect.ConnectAsync(userbot);

                    var userId = userbot.GetUserId();
                    if (userId != null)
                    {
                        GlobalVariables.Bots[userId.Value] = new TelegramBotAbstract(client,
                                                                                     userbot.GetWebsite(), userbot.GetContactString(), userId.Value, BotTypeApi.USER_BOT);

                        _ = TestThingsAsync(userId.Value);
                    }
                    else
                    {
                        try
                        {
                            client.Dispose();
                        }
                        catch
                        {
                            ;
                        }
                    }
                }
            }

            if (_botDisguisedAsUserBotInfos != null && advancedModeDebugDisguised)
            {
                foreach (var userbot in _botDisguisedAsUserBotInfos)
                {
                    var client = await UserbotConnect.ConnectAsync(userbot);

                    var userId = userbot.GetUserId();
                    if (userId != null)
                    {
                        GlobalVariables.Bots[userId.Value] = new TelegramBotAbstract(client,
                                                                                     userbot.GetWebsite(), userbot.GetContactString(), userId.Value,
                                                                                     BotTypeApi.DISGUISED_BOT);

                        _ = TestThingsDisguisedAsync(userId.Value);
                    }
                    else
                    {
                        try
                        {
                            client.Dispose();
                        }
                        catch
                        {
                            ;
                        }
                    }
                }
            }

            if (GlobalVariables.Bots.Keys.Count > 0)
            {
                var t = new Thread(CheckMessagesToSend);
                t.Start();
            }
        }
Exemplo n.º 16
0
        public IActionResult CreateNewBotForSales(TokenChange tokenModel, BotType botType)
        {
            int accountId = (int)HttpContext.Items["accountId"];

            try
            {
                string token         = tokenModel?.Token;
                string botUsername   = new TelegramBotClient(token).GetMeAsync().Result.Username;
                string jsonBotMarkup = localizer[botType.ToString()];

                int statusGroupId = contextDb.OrderStatusGroups.First(stat => stat.OwnerId == accountId).Id;



                //нужно установить групппу статусов
                if (jsonBotMarkup.Contains("1000001"))
                {
                    jsonBotMarkup = jsonBotMarkup.Replace("1000001", statusGroupId.ToString());
                }


                BotDB bot = new BotDB
                {
                    OwnerId = accountId,
                    BotType = "BotForSales",
                    Token   = token,
                    BotName = botUsername,
                    Markup  = jsonBotMarkup
                };

                contextDb.Bots.Add(bot);

                //Создание статистики для бота
                BotForSalesStatistics botForSalesStatistics = new BotForSalesStatistics
                {
                    Bot = bot, NumberOfOrders = 0, NumberOfUniqueMessages = 0, NumberOfUniqueUsers = 0
                };

                contextDb.BotForSalesStatistics.Add(botForSalesStatistics);

                try
                {
                    contextDb.SaveChanges();
                }
                catch (Exception exception)
                {
                    throw new TokenMatchException("Возможно в базе уже есть этот бот", exception);
                }

                return(RedirectToAction("SalesTreeEditor", "BotForSalesEditing", new { botId = bot.Id }));
            }
            catch (TokenMatchException ex)
            {
                logger.Log(LogLevel.USER_ERROR, Source.WEBSITE, $"Сайт. Создание нового бота. При " +
                           $"запросе botUsername было выброшено исключение (возможно, введённый" +
                           $"токен был специально испорчен)" + ex.Message, accountId: accountId);

                ModelState.AddModelError("", "Этот бот уже зарегистрирован.");
            }
            catch (Exception ee)
            {
                logger.Log(LogLevel.USER_ERROR, Source.WEBSITE, $"Сайт. Создание нового бота. При " +
                           $"запросе botUsername было выброшено исключение (возможно, введённый" +
                           $"токен был специально испорчен)" + ee.Message, accountId: accountId);

                ModelState.AddModelError("", "Ошибка обработки токена.");
            }


            return(View("BotForSalesTokenEntry"));
        }
 public double GetScore(Message message, TelegramBotClient botClient)
 => message.GetMatch("art", "picture", "image", "artwork", "painting", "арт", "картина", "пикча");
Exemplo n.º 18
0
 public Telegram()
 {
     client = new TelegramBotClient("863527488:AAGGG6slmQuQnpnX4vTi_bIeO-O7FfPn4CU");
     LoadSettings();
 }
Exemplo n.º 19
0
 public WhoisCommand(AclService aclService, TelegramBotClient botClient)
 {
     this.aclService = aclService;
     this.botClient  = botClient;
 }
Exemplo n.º 20
0
 public CallBackOrders(TelegramBotClient client, MainProvider provider) : base(client, provider)
 {
 }
Exemplo n.º 21
0
        Regex rxNums = new Regex(@"^\d+$"); // проверка на число


        public CommandProcessor(TelegramBotClient bot)
        {
            Bot      = bot;
            Gen      = new Randomiser();
            ImageGen = new ImageGenerator();
        }
        public static async void Init()
        {
            groups = new List <Group>();

            Client = new TelegramBotClient(AppSettings.Token);

            commands = new List <Command>()
            {
                new HelloCommand(),
                new AddCommand(),
                new DutyListCommand(),
                new NextCommand(),
                new CurrentCommand(),
                new PushCommand(),
                new CancelCommand(),
                new MakeCommand(),
                new ListCommand(),
                new TripleDotCommand(),
                new SetCommand(),
                new ExcludeCommand(),
                new HelpCommand(),
                new DeleteCommand(),
                new StartCommand(),
                new ForceOneCommand(),
                new AssociateCommand(),
                new WhenCommand(),
                new WhoCommand(),
                new ChangeCommand()
            };


            var avaibleCommands = DutyBot.Commands
                                  .Where(c => c.WhoCanExecute.Contains(ChatMemberStatus.Member))
                                  .Select(c => c.Name.ToLower());

            var avaibleList = Properties.Resources.Сommands
                              .Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries)
                              .Where(s => avaibleCommands
                                     .Contains(s.Split(new char[] { '-', ' ' }, StringSplitOptions.RemoveEmptyEntries)[0]));

            await Client.SetMyCommandsAsync(
                avaibleList.Select(s =>
            {
                var commandDescription = s.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);

                if (s.Trim()[0] == '#')
                {
                    return(null);
                }

                return(new BotCommand()
                {
                    Command = commandDescription[0].Trim(),
                    Description = commandDescription.Length == 2 ? commandDescription[1].Trim() : "нет описания"
                });
            })
                .Where(bc => bc != null));

            Client.StartReceiving();
            Client.OnMessage += OnNewMessage;
        }
 public BotService(string token, string webhookUrl)
 {
     Client = new TelegramBotClient(token);
     Client.SetWebhookAsync(webhookUrl).Wait();
 }
Exemplo n.º 24
0
        public override async Task Execute(Message message, TelegramBotClient client)
        {
            var chatId = message.Chat.Id;

            await client.SendTextMessageAsync(chatId, "Hello");
        }
Exemplo n.º 25
0
        static void ConnectBot(string funcName)
        {
            if (botClient != null) {
                try {
                    botClient.StopCheckUpdates ();
                } catch (Exception ex) {

                }
                botClient = null;
            }
            StLog.DebugWriteLine ("Erstelle BotClient", funcName);
            botClient = new TelegramBotClient() {
                Token = "120746059:AAF8jzbIKrUdUJe2IG85lQPQHPRU7-jGrK8",
                CheckInterval=1000
            };

            // Hier stürzte er ab, wenn keine Verbindung zum iNet besteht !!
            StLog.DebugWriteLine ("Prüfe Verbindung", funcName);
            _connectTimer = null;
            try {
                var me = botClient.GetMe ().FirstName;
                StLog.DebugWriteLine ("Telegram Antwort [" + me + "]", funcName);
            }
            catch (Exception ex) {
                StLog.DebugWriteLine (ex.Message, funcName);

                if (_connectTimer == null) {
                    _connectTimer = new Timer (delegate {
                        botClient.UpdatesReceived -= telegramUpdateReceived;
                        botClient.GetUpdatesError -= BotClient_GetUpdatesError;

                        ConnectBot ("ConnectBot():RETRY");
                    }, null, 5000, System.Threading.Timeout.Infinite);
                }
            }
            finally {
                if (_connectTimer == null) {
                    StLog.DebugWriteLine ("Generiere Update Event", funcName);

                    botClient.UpdatesReceived -= telegramUpdateReceived;
                    botClient.GetUpdatesError -= BotClient_GetUpdatesError;
                    botClient.UpdatesReceived += telegramUpdateReceived;
                    botClient.GetUpdatesError += BotClient_GetUpdatesError;
                    StLog.DebugWriteLine ("Starte Updateprüfung", funcName);
                    botClient.StartCheckingUpdates ();
                }
            }
        }
        public static async Task Execute(Message message, TelegramBotClient client)
        {
            var chatId = message.Chat.Id;

            string key      = string.Empty;
            string name     = OtionalText;
            string dateTime = OtionalText;
            string place    = OtionalText;
            string info     = OtionalText;
            int    count    = 0;

            await client.SendChatActionAsync(chatId, ChatAction.Typing);

            using (TelegramChatContext db = new TelegramChatContext())
            {
                try
                {
                    var secretEvent = await db.Events.FirstOrDefaultAsync(x => x.HostChatId == chatId);

                    if (secretEvent != null)
                    {
                        key = secretEvent.InviteKey;
                        if (!string.IsNullOrWhiteSpace(secretEvent.Name))
                        {
                            name = secretEvent.Name;
                        }

                        if (!string.IsNullOrWhiteSpace(secretEvent.Date))
                        {
                            dateTime = secretEvent.Date;
                        }

                        if (!string.IsNullOrWhiteSpace(secretEvent.Place))
                        {
                            place = secretEvent.Place;
                        }

                        if (!string.IsNullOrWhiteSpace(secretEvent.Info))
                        {
                            info = secretEvent.Info;
                        }

                        count = secretEvent.Participants.Count();
                        secretEvent.ParticipantsCount = count;
                        await db.SaveChangesAsync();

                        await client.SendTextMessageAsync(chatId, string.Format(StatusMessageText, key, name, dateTime, place, info, count), ParseMode.MarkdownV2);
                    }
                    else
                    {
                        await client.SendTextMessageAsync(chatId, @"You have to start registration using command /register");
                    }
                }
                catch (Exception e)
                {
                    Debug.WriteLine($"{nameof(RegistrationStatus)}:{e.Message}");
                    if (e.InnerException != null)
                    {
                        Debug.WriteLine(e.InnerException);
                    }
                }
            }
        }
Exemplo n.º 27
0
        public Cleverbot(Instance db, Setting settings, TelegramBotClient bot)
        {
            var me = bot.GetMeAsync().Result;

            bot.OnUpdate += (sender, args) =>
            {
                new Task(() =>
                {
                    if (!Enabled)
                    {
                        return;
                    }
                    try
                    {
                        //check to see if it was to me, a reply to me, whatever
                        var message = args.Update.Message;
                        if (message.Date < DateTime.UtcNow.AddSeconds(-10))
                        {
                            return;
                        }
                        if (message?.Text == null)
                        {
                            return;
                        }
                        var text = message.Text.ToLower();

                        if (text.StartsWith("!") || text.StartsWith("/"))
                        {
                            return;                                               //ignore commands
                        }
                        if (message.Chat.Type != ChatType.Private && message.Chat.Id != -1001119386963)
                        {
                            return;
                        }

                        if (text.Contains(me.FirstName.ToLower()) || text.Contains(me.Username.ToLower()) ||
                            message.ReplyToMessage?.From.Id == me.Id || message.Chat.Type == ChatType.Private)
                        {
                            text         = text.Replace(me.FirstName.ToLower(), "Mitsuku").Replace("@", "").Replace(me.Username.ToLower(), "Mitsuku");
                            var response =
                                Encoding.UTF8.GetString(
                                    new WebClient().UploadValues(
                                        "https://kakko.pandorabots.com/pandora/talk?botid=f326d0be8e345a13&skin=chat",
                                        new NameValueCollection()
                            {
                                { "message", text }
                            }));
                            var matches = Regex.Matches(response, "(Мitsuku:</B>(.*))");
                            var match   = matches[0].Value;

                            match =
                                match.Replace("Мitsuku:", "")
                                .Replace("</B> ", "")
                                .Replace(" .", ".")
                                .Replace("<br>", "  ")
                                .Replace("Mitsuku", "Seras")
                                .Replace("Мitsuku", "Seras")
                                .Replace(" < P ALIGN=\"CENTER\">", "")
                                .Replace("</P>", " ")
                                .Trim();
                            match = match.Replace("<B>", "```").Replace("You:", "").Replace("Μitsuku:", "").Trim();
                            match = match.Replace("Mousebreaker", "Para");

                            //[URL]http://www.google.co.uk/search?hl=en&amp;q=dot net&amp;btnI=I%27m+Feeling+Lucky&amp;meta=[/URL]
                            if (match.Contains("[URL]"))
                            {
                                //parse out the url
                                var url = Regex.Match(match, @"(\[URL\].*\[/URL\])").Value;
                                match   = "[" + match.Replace(url, "") + "]";
                                url     = url.Replace("[URL]", "").Replace("[/URL]", "").Replace(".co.uk", ".com");
                                match  += $"({url})"; //markdown linking
                                Console.WriteLine(match);

                                bot.SendTextMessageAsync(args.Update.Message.Chat.Id, match, replyToMessageId: message.MessageId, parseMode: ParseMode.Markdown);
                            }
                            //<P ALIGN="CENTER"><img src="http://www.square-bear.co.uk/mitsuku/gallery/donaldtrump.jpg"></img></P>
                            else if (match.Contains("img src=\""))
                            {
                                var img = Regex.Match(match, "<img src=\"(.*)\"></img>").Value;
                                match   = match.Replace(img, "").Replace("<P ALIGN=\"CENTER\">", "").Trim();

                                ;
                                img = img.Replace("<img src=\"", "").Replace("\"></img>", "");
                                //download the photo
                                var filename = args.Update.Message.MessageId + ".jpg";
                                new WebClient().DownloadFile(img, filename);
                                //create the file to send
                                var f2S = new FileToSend(filename, new FileStream(filename, FileMode.Open, FileAccess.Read));
                                Console.WriteLine(match);
                                bot.SendPhotoAsync(args.Update.Message.Chat.Id, f2S, match);
                                //bot.SendTextMessageAsync(args.Update.Message.Chat.Id, match);
                            }
                            else
                            {
                                Console.WriteLine(match);
                                bot.SendTextMessageAsync(args.Update.Message.Chat.Id, match, replyToMessageId: message.MessageId, parseMode: ParseMode.Markdown);
                            }
                        }
                    }
                    catch
                    {
                        // ignored
                    }
                }).Start();
            };
        }
Exemplo n.º 28
0
 public abstract Task ExecuteAsync(Message message, TelegramBotClient botClient);
Exemplo n.º 29
0
 public SyncService(IServiceScopeFactory serviceScopeFactory)
 {
     _serviceScopeFactory = serviceScopeFactory;
     _client = new TelegramBotClient(Secrets.TelegramToken);
 }
Exemplo n.º 30
0
        public async Task <bool> ExecuteAsync(TelegramBotClient botClient, Update update)
        {
            try
            {
                Conf.Update Latest = Conf.CheckForUpdates();
                if (Conf.IsNewerVersionAvailable(Latest))
                {
                    string UpdateString = Vars.CurrentLang.Message_UpdateAvailable
                                          .Replace("$1", Latest.Latest)
                                          .Replace("$2", Latest.Details);
                    await botClient.SendTextMessageAsync(
                        update.Message.From.Id,
                        UpdateString, ParseMode.Markdown,
                        false,
                        Vars.CurrentConf.DisableNotifications,
                        update.Message.MessageId);

                    // where difference begins
                    await botClient.SendTextMessageAsync(
                        update.Message.From.Id,
                        Vars.CurrentLang.Message_UpdateProcessing,
                        ParseMode.Markdown,
                        false,
                        Vars.CurrentConf.DisableNotifications,
                        update.Message.MessageId);

                    // download compiled package
                    Log("Starting update download... (pmcenter_update.zip)", "BOT");
                    WebClient Downloader = new WebClient();
                    Downloader.DownloadFile(
                        new Uri(Vars.UpdateArchiveURL),
                        Path.Combine(Vars.AppDirectory, "pmcenter_update.zip"));
                    Log("Download complete. Extracting...", "BOT");
                    using (ZipArchive Zip = ZipFile.OpenRead(Path.Combine(Vars.AppDirectory, "pmcenter_update.zip")))
                    {
                        foreach (ZipArchiveEntry Entry in Zip.Entries)
                        {
                            Log("Extracting: " + Path.Combine(Vars.AppDirectory, Entry.FullName), "BOT");
                            Entry.ExtractToFile(Path.Combine(Vars.AppDirectory, Entry.FullName), true);
                        }
                    }
                    if (Vars.CurrentConf.AutoLangUpdate)
                    {
                        Log("Starting automatic language file update...", "BOT");
                        await Downloader.DownloadFileTaskAsync(
                            new Uri(Vars.CurrentConf.LangURL),
                            Path.Combine(Vars.AppDirectory, "pmcenter_locale.json")
                            );
                    }
                    Log("Cleaning up temporary files...", "BOT");
                    System.IO.File.Delete(Path.Combine(Vars.AppDirectory, "pmcenter_update.zip"));
                    await botClient.SendTextMessageAsync(
                        update.Message.From.Id,
                        Vars.CurrentLang.Message_UpdateFinalizing,
                        ParseMode.Markdown,
                        false,
                        Vars.CurrentConf.DisableNotifications,
                        update.Message.MessageId);

                    Log("Exiting program... (Let the daemon do the restart job)", "BOT");
                    try
                    {
                        Environment.Exit(0);
                        return(true);
                    }
                    catch (Exception ex)
                    {
                        Log("Failed to execute restart command: " + ex.ToString(), "BOT", LogLevel.ERROR);
                        return(true);
                    }
                    // end of difference
                }
                else
                {
                    await botClient.SendTextMessageAsync(
                        update.Message.From.Id,
                        Vars.CurrentLang.Message_AlreadyUpToDate
                        .Replace("$1", Latest.Latest)
                        .Replace("$2", Vars.AppVer.ToString())
                        .Replace("$3", Latest.Details),
                        ParseMode.Markdown,
                        false,
                        Vars.CurrentConf.DisableNotifications,
                        update.Message.MessageId);

                    return(true);
                }
            }
            catch (Exception ex)
            {
                string ErrorString = Vars.CurrentLang.Message_UpdateCheckFailed.Replace("$1", ex.ToString());
                await botClient.SendTextMessageAsync(
                    update.Message.From.Id,
                    ErrorString,
                    ParseMode.Markdown,
                    false,
                    Vars.CurrentConf.DisableNotifications,
                    update.Message.MessageId);

                return(true);
            }
        }
Exemplo n.º 31
0
 public async void SendMessage(TelegramBotClient botClient)
 {
     await Task.Run(() => botClient.EditMessage(_message.From.Id, user.MessageId, TextMessage, "53 - Russian", user, replyMarkup: InlineButton.Start()));
 }
        public async override Task OnTextData(TelegramBotClient client, Message message)
        {
            var chatId  = message.Chat.Id;
            var platoon = DutyBot.GetGroupByChatId(chatId)?.Platoon;

            if (platoon == null)
            {
                throw new InvalidIdException("Взаимодействие с данной группой не было инициировано.");
            }

            if (_keyboardShown)
            {
                var markupMessage = await client.SendTextMessageAsync(chatId, $"Выбран {message.Text}",
                                                                      replyMarkup : new ReplyKeyboardRemove());

                await client.DeleteMessageAsync(chatId, markupMessage.MessageId);

                _keyboardShown = false;
            }

            if (Data.Trim().ToLower() == "all")
            {
                if (IgnoreAllArgument)
                {
                    Student    = null;
                    LastStatus = CommandStatus.AwaitExecuting;
                    return;
                }
                else
                {
                    await client.SendTextMessageAsync(chatId, "Данная команда не поддерживает \"all\"!\n" +
                                                      "Введите имя или фамилию студента)");

                    LastStatus = CommandStatus.AwaitNextMessage;
                    return;
                }
            }

            Student[] students = null;

            if (_students == null)
            {
                students = _students = platoon.GetStudents(Data);
            }
            else
            {
                students = _students.Where(s => s.RecognizeSelf(Data)).ToArray();
            }

            if (students.Length == 0)
            {
                await client.SendTextMessageAsync(message.Chat.Id, $"{Data} отсутсвует в списке студентов!");

                LastStatus = CommandStatus.AwaitNextMessage;
                _students  = null;
                return;
            }

            if (students.Length != 1)
            {
                var studentsMessage = new StringBuilder("По введённым данным невозможно однозначно определить студента!\n" +
                                                        "Кого именно имели в виду?\n");

                foreach (var student in students)
                {
                    studentsMessage.Append($"{student},\n");
                }

                studentsMessage
                .Remove(studentsMessage.Length - 2, 2)
                .Append('.');

                bool equalsName = true;

                if (students[0].Surname == students[1].Surname)
                {
                    equalsName = false;
                }

                var keyboard = new ReplyKeyboardMarkup(students
                                                       .Select(s => new KeyboardButton(equalsName ? s.Surname : s.Name)), true, true)
                {
                    Selective = true
                };

                await client.SendTextMessageAsync(message.Chat.Id,
                                                  $"{studentsMessage}", replyMarkup : keyboard, replyToMessageId : message.MessageId);

                _keyboardShown = true;

                LastStatus = CommandStatus.AwaitNextMessage;
                return;
            }

            _students  = null;
            Student    = students.Single();
            LastStatus = CommandStatus.AwaitExecuting;
        }
        public void SendMessage(TelegramBotClient botClient)
        {
            InlineButton inlineButton = new InlineButton();

            botClient.EditMessage(user.ID, user.MessageID, "Идет обработка, это может занят некоторое время...", "39 - AddPhotoInDataBase", user);
        }