public static async Task <string> DownloadFile(ITelegramBotClient botClient, File file, long chatId)
        {
            try
            {
                string originalPath = file.FilePath;
                string fileName     = originalPath.Substring(originalPath.LastIndexOf("/", StringComparison.Ordinal) + 1);

                string pathToCodeRecognitionDirectory = Path.Combine(Environment.CurrentDirectory, "Code_recognition_photo");
                string pathToFile = Path.Combine(pathToCodeRecognitionDirectory, $"{chatId}_{fileName}");

                Directory.CreateDirectory(pathToCodeRecognitionDirectory);
                using (FileStream outputFile = System.IO.File.Create(pathToFile))
                {
                    await botClient.DownloadFileAsync(originalPath, outputFile);
                }

                return(pathToFile);
            }
            catch (Exception e)
            {
                //  Ignore
            }

            return(null);
        }
        public ProductPhoto InsertAdditionallPhoto(int ProductId, Telegram.Bot.Types.File Photo, string Caption = null)
        {
            byte[] PhotoByte = null;

            AttachmentFs attachmentFs = null;

            ProductPhoto productPhoto = null;

            try
            {
                if (ProductId > 0 && Photo != null)
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        Photo.FileStream.CopyTo(ms);
                        PhotoByte = ms.ToArray();
                    }

                    if (PhotoByte != null)
                    {
                        attachmentFs = InsertAttachmentFs(PhotoByte, Caption: Caption);
                    }

                    if (attachmentFs != null)
                    {
                        productPhoto = new ProductPhoto
                        {
                            AttachmentFsId = attachmentFs.Id,
                            ProductId      = ProductId
                        };

                        db.ProductPhoto.Add(productPhoto);

                        db.SaveChanges();
                    }

                    return(productPhoto);
                }

                return(null);
            }

            catch
            {
                return(null);
            }
        }
Esempio n. 3
0
        public Audio FromTelegramAudio(Telegram.Bot.Types.Audio v)
        {
            if (v == null)
            {
                return(null);
            }

            System.IO.Stream stream = v.FileStream;
            if (stream == null)
            {
                Telegram.Bot.Types.File f = TClient.GetFileAsync(v.FileId).Result;
                stream = f.FileStream;
            }

            Audio audio = new Audio(v.Title, v.Performer, v.Duration, stream);

            return(audio);
        }
Esempio n. 4
0
        public Voice FromTelegramVoice(Telegram.Bot.Types.Voice v)
        {
            if (v == null)
            {
                return(null);
            }
            Voice voice = new Voice(Voice.VoiceAudioType.OggOpus);

            if (v.FileStream == null)
            {
                Telegram.Bot.Types.File f = TClient.GetFileAsync(v.FileId).Result;
                voice.AudioStream = f.FileStream;
            }
            else
            {
                voice.AudioStream = v.FileStream;
            }
            voice.Duration = v.Duration;

            return(voice);
        }
Esempio n. 5
0
        private async void BotOnMessageReceived(object sender, MessageEventArgs args)
        {
            Telegram.Bot.Types.Message message = args.Message;
            if (message.Type == MessageType.Document && userStep.ContainsKey(message.From.Id) && userStep[message.From.Id] == 1)
            {
                Telegram.Bot.Types.File file = await Bot.GetFileAsync(message.Document.FileId);

                try
                {
                    string content;
                    using (var client = new WebClient())
                        content = await client.DownloadStringTaskAsync($"https://api.telegram.org/file/bot{token}/{file.FilePath}");
                    InstaShitCore.Settings settings = JsonConvert.DeserializeObject <InstaShitCore.Settings>(content);
                    if (Directory.Exists(Path.Combine(assemblyLocation, settings.Login)))
                    {
                        await SendMessageAsync(message.From.Id, "This user is already registered. " +
                                               "If you have recently unregisted from this bot, you have to wait up to 24 hours " +
                                               "before registering again.");

                        return;
                    }
                    if (settings.MinimumSleepTime < 3000 || settings.MinimumSleepTime > 10000)
                    {
                        await SendMessageAsync(message.Chat.Id, "MinimumSleepTime must be at least " +
                                               "3000 but no more than 10000.");

                        return;
                    }
                    if (settings.MaximumSleepTime < 5000 || settings.MaximumSleepTime > 15000)
                    {
                        await SendMessageAsync(message.Chat.Id, "MaximumSleepTime must be at least " +
                                               "5000 but no more than 15000.");

                        return;
                    }
                    if (settings.MaximumSleepTime - settings.MinimumSleepTime < 2000)
                    {
                        await SendMessageAsync(message.Chat.Id, "The difference between " +
                                               "MaximumSleepTime and MinimumSleepTime must be at least 2000 and " +
                                               "MaximumSleepTime must be greater than MinimumSleepTime.");

                        return;
                    }
                    InstaShit instaShit = new InstaShit(settings);
                    if (!await instaShit.TryLoginAsync())
                    {
                        await SendMessageAsync(message.Chat.Id, "Incorrect login or password.");

                        return;
                    }
                    Directory.CreateDirectory(Path.Combine(assemblyLocation, settings.Login));
                    File.WriteAllText(Path.Combine(assemblyLocation, settings.Login, "settings.json"), JsonConvert.SerializeObject(settings, Formatting.Indented));
                    userStep.Remove(message.From.Id);
                    User user = new User()
                    {
                        Login  = settings.Login,
                        UserId = message.From.Id
                    };
                    users.Add(user);
                    await SendMessageAsync(message.Chat.Id, "User successfully added!\n" +
                                           "You'll be added to queue at the next queue refresh (9:00 Polish time every day).");
                }
                catch
                {
                    await SendMessageAsync(message.Chat.Id, "An error occured while trying to get settings. " +
                                           "Make sure you're sending the right file.");
                }
            }
            if (message.Type == MessageType.Text)
            {
                Log.Write($"Received message from user {message.From.Id}: {message.Text}", LogType.Communication);
                switch (message.Text.ToLower())
                {
                case "/start":
                    await SendMessageAsync(message.Chat.Id, "Hi! I'm InstaShit, a bot " +
                                           "for Insta.Ling which automatically solves daily sessions.\nTo get started, " +
                                           " type /configure. For more information, type /help.");

                    break;

                case "/configure":
                    if (users.Any(u => u.UserId == message.From.Id))
                    {
                        await SendMessageAsync(message.Chat.Id, "Already configured.");

                        return;
                    }
                    if (!userStep.ContainsKey(message.From.Id))
                    {
                        if (useWhitelist)
                        {
                            userStep.Add(message.From.Id, 4);
                            await SendMessageAsync(message.Chat.Id, "This instance of InstaShit.Bot has whitelisting " +
                                                   "enabled. Please enter the unique key received from the server administrator. " +
                                                   "If you don't have it, contact server's owner or use another instance of the " +
                                                   "bot which is publically available.\nTo abort, type /cancel.");
                        }
                        else
                        {
                            userStep.Add(message.From.Id, 1);
                            await SendMessageAsync(message.Chat.Id, "Please attach the InstaShit settings file.\n" +
                                                   "You can use InstaShit.CLI to generate it. You can also " +
                                                   "share settings directly from InstaShit.Android " +
                                                   "(since version 0.5) - just go to \"Edit settings\", \"Advanced mode\" " +
                                                   "and touch \"Share\" button. Ability to create new settings directly " +
                                                   "from bot coming soon!\nType /cancel to abort this action.");
                        }
                    }
                    break;

                case "/dictionary":
                    var user = users.FirstOrDefault(u => u.UserId == message.From.Id);
                    if (user == null)
                    {
                        await SendMessageAsync(message.Chat.Id, "No configuration found.");

                        return;
                    }
                    if (File.Exists(Path.Combine(assemblyLocation, user.Login, "wordsDictionary.json")))
                    {
                        await SendFileAsync(message.Chat.Id, Path.Combine(assemblyLocation, user.Login, "wordsDictionary.json"));
                    }
                    else
                    {
                        await SendMessageAsync(message.Chat.Id, "Dictionary file doesn't exist.");
                    }
                    break;

                case "/cancel":
                    if (userStep.ContainsKey(message.From.Id))
                    {
                        userStep.Remove(message.From.Id);
                        await SendMessageAsync(message.Chat.Id, "Cancelled!");
                    }
                    break;

                case "/remove":
                    if (!users.Any(u => u.UserId == message.From.Id))
                    {
                        await SendMessageAsync(message.Chat.Id, "No configuration found.");

                        return;
                    }
                    if (!userStep.ContainsKey(message.From.Id))
                    {
                        userStep.Add(message.From.Id, 2);
                        await SendMessageAsync(message.Chat.Id, "You can stop automatic InstaShit session " +
                                               "solving if you wish. Please note that this action won't cancel ongoing InstaShit session, " +
                                               "if there's any.\nIf you want to continue, type /remove again. " +
                                               "To cancel, type /cancel.");
                    }
                    else if (userStep[message.From.Id] == 2)
                    {
                        userStep.Remove(message.From.Id);
                        User userToRemove = users.Find(u => u.UserId == message.From.Id);
                        users.Remove(userToRemove);
                        try
                        {
                            Directory.Delete(Path.Combine(assemblyLocation, userToRemove.Login), true);
                            await SendMessageAsync(message.Chat.Id, "Successfully removed.");
                        }
                        catch
                        {
                            await Task.Delay(3000);

                            try
                            {
                                Directory.Delete(Path.Combine(assemblyLocation, userToRemove.Login), true);
                                await SendMessageAsync(message.Chat.Id, "Successfully removed.");
                            }
                            catch (Exception ex)
                            {
                                Log.Write("ERROR: " + ex, LogType.Communication);
                                await SendMessageAsync(message.Chat.Id, "An error occured while trying to remove " +
                                                       "your files. The administrator has been notifies about this issue.");
                            }
                        }
                    }
                    break;

                case "/skip":
                    if (!users.Any(u => u.UserId == message.From.Id))
                    {
                        await SendMessageAsync(message.Chat.Id, "No configuration found.");

                        return;
                    }
                    if (usersToSkip.Contains(users.Find(u => u.UserId == message.From.Id).Login))
                    {
                        await SendMessageAsync(message.Chat.Id, "Already on the skip list.");

                        return;
                    }
                    if (!userStep.ContainsKey(message.From.Id))
                    {
                        userStep.Add(message.From.Id, 3);
                        await SendMessageAsync(message.Chat.Id, "You can skip the next InstaShit session if you wish. " +
                                               " Please note that this action won't cancel ongoing InstaShit session, if there's any." +
                                               "\nIf you want to continue, type /skip again. To cancel, type /cancel.");
                    }
                    else if (userStep[message.From.Id] == 3)
                    {
                        userStep.Remove(message.From.Id);
                        usersToSkip.Add(users.Find(u => u.UserId == message.From.Id).Login);
                        await SendMessageAsync(message.Chat.Id, "Successfully added to skip list.");
                    }
                    break;

                default:
                    if (userStep.ContainsKey(message.From.Id) && userStep[message.From.Id] == 4)
                    {
                        if (whitelist.Any(t => t.Item1 == message.Text))
                        {
                            whitelist.Remove(whitelist.Find(t => t.Item1 == message.Text));
                            userStep[message.From.Id] = 1;
                            await SendMessageAsync(message.Chat.Id, "Success!");
                            await SendMessageAsync(message.Chat.Id, "Please attach the InstaShit settings file.\n" +
                                                   "You can use InstaShit.CLI to generate it. You can also share settings directly " +
                                                   "from InstaShit.Android (since version 0.5) - just go to \"Edit settings\", " +
                                                   "\"Advanced mode\" and touch \"Share\" button. Ability to create new settings " +
                                                   "using the bot coming soon!\nType /cancel to abort this action (you'll need " +
                                                   "a new unique key if you try to configure the bot again in the future).");
                        }
                        else
                        {
                            await SendMessageAsync(message.Chat.Id, "Incorrect key.");
                        }
                        break;
                    }
                    await SendMessageAsync(message.Chat.Id, "Usage:\n" +
                                           "/configure - Configures InstaShit bot\n" +
                                           "/skip - Skips next InstaShit session\n" +
                                           "/remove - Unregisters from the bot\n" +
                                           "/cancel - Cancels any ongoing process (configure/remove/skip)\n" +
                                           "/dictionary - Returns the wordsDictionary.json file");

                    break;
                }
            }
        }
Esempio n. 6
0
        public Poll ReadPoll(Telegram.Bot.Types.File file)
        {
            StreamReader sr   = new StreamReader(file.FileStream);
            string       text = "";

            while (!text.Contains("Type"))
            {
                text = sr.ReadLine();
            }
            string[] tempText = text.Split('=');
            int      type     = Convert.ToInt32(tempText[1].Trim());

            Poll.PollType enmType = (Poll.PollType)type;

            while (!text.Contains("Pass"))
            {
                text = sr.ReadLine();
            }
            tempText = text.Split('=');
            string password = tempText[1].Trim();

            text = "";
            while (!text.Contains("QCount"))
            {
                text = sr.ReadLine();
            }
            tempText = text.Split('=');
            int numberOfQuestions = Convert.ToInt32(tempText[1].Trim());

            Poll poll = new Poll("test", "abc", numberOfQuestions);


            int i = 1;

            while (!sr.EndOfStream)
            {
                text = sr.ReadLine();
                if (text.StartsWith($"Q{i}"))
                {
                    string questionContent = text.Substring(text.IndexOf(':') + 1);

                    while (!text.StartsWith("ACount"))
                    {
                        text = sr.ReadLine();
                    }
                    int aCount = Convert.ToInt32(text.Substring(text.IndexOf('=') + 1));

                    while (!text.StartsWith("QType"))
                    {
                        text = sr.ReadLine();
                    }
                    string qType1 = text.Substring(text.IndexOf('=') + 1);
                    Question.QuestionType qType = (Question.QuestionType)Enum.Parse(typeof(Question.QuestionType), qType1);

                    Question question = new Question(questionContent, qType, aCount);
                    poll.Questions.Add(question);

                    int j = 1;
                    while (!text.StartsWith("}"))
                    {
                        text = sr.ReadLine();
                        if (text.StartsWith($"A{j}"))
                        {
                            string tempAnswer = text.Substring(text.IndexOf(':') + 1).Trim();
                            Answer answer     = new Answer(tempAnswer);
                            poll.Questions[i - 1].Answers.Add(answer);
                            j++;
                        }
                    }
                    j = 1;
                    i++;
                }
            }
            foreach (var it in poll.Questions)
            {
                Console.WriteLine(it);
            }

            return(poll);
        }
Esempio n. 7
0
        static async Task <bool> WriteBookOrImgFileAsync(MessageEventArgs e)
        {
            Telegram.Bot.Types.File book = null;
            FileStream fs      = null;
            string     imgPath = "";
            int        imgW    = 1;
            int        imgH    = 1;

            try
            {
                if (e.Message.Type == Telegram.Bot.Types.Enums.MessageType.Document)
                {
                    book = await bot.GetFileAsync(e.Message.Document.FileId);

                    if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                    {
                        fs = new FileStream(LinuxPath + e.Message.Document.FileName, FileMode.Create);
                    }
                    else
                    {
                        fs = new FileStream(WindowsPath + e.Message.Document.FileName, FileMode.Create);
                    }
                    Log("book or file: " + e.Message.Document.FileName);
                }

                if (e.Message.Type == Telegram.Bot.Types.Enums.MessageType.Photo)
                {
                    book = await bot.GetFileAsync(e.Message.Photo[0].FileId);

                    imgW = e.Message.Photo[0].Width;
                    imgH = e.Message.Photo[0].Height;
                    if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                    {
                        fs      = new FileStream(LinuxPath + "image" + e.Message.Photo[0].FileId + ".jpeg", FileMode.Create);
                        imgPath = LinuxPath + "image" + e.Message.Photo[0].FileId + ".jpeg";
                    }
                    else
                    {
                        fs      = new FileStream(WindowsPath + "image" + e.Message.Photo[0].FileId + ".jpeg", FileMode.Create);
                        imgPath = WindowsPath + "image" + e.Message.Photo[0].FileId + ".jpeg";
                    }
                    Log("book or file: " + "image" + e.Message.Photo[0].FileId);
                }
            }


            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                await bot.SendTextMessageAsync(new Telegram.Bot.Types.ChatId(userAndChatID), "book or file is not saved " + ex.Message + "\n" + ex.StackTrace);

                return(false);
            }



            await bot.DownloadFileAsync(book.FilePath, fs);

            fs.Close();
            fs.Dispose();
            if (e.Message.Caption == "resize")
            {
                await bot.SendTextMessageAsync(new Telegram.Bot.Types.ChatId(userAndChatID), "wait a few minutes resizying image. You give a notification when will done.");

                ResizeImage(imgPath, imgW, imgH);
            }

            Console.WriteLine("book or file name add to log");
            await bot.SendTextMessageAsync(new Telegram.Bot.Types.ChatId(userAndChatID), "book or file was save");

            return(true);
        }