当前位置: 首页>>代码示例>>C#>>正文


C# Api.SendTextMessage方法代码示例

本文整理汇总了C#中Api.SendTextMessage方法的典型用法代码示例。如果您正苦于以下问题:C# Api.SendTextMessage方法的具体用法?C# Api.SendTextMessage怎么用?C# Api.SendTextMessage使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Api的用法示例。


在下文中一共展示了Api.SendTextMessage方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Run

        static async Task Run()
        {
            var Bot = new Api("Your Api Key");

            var me = await Bot.GetMe();

            Console.WriteLine("Hello my name is {0}", me.Username);

            var offset = 0;

            while (true)
            {
                var updates = await Bot.GetUpdates(offset);

                foreach (var update in updates)
                {
                    if (update.Message.Text != null)
                        await Bot.SendTextMessage(update.Message.Chat.Id, update.Message.Text);

                    offset = update.Id + 1;
                }

                await Task.Delay(1000);
            }

        }
开发者ID:lftkv,项目名称:telegram.bot,代码行数:26,代码来源:Program.cs

示例2: ConnectTask

 private static void ConnectTask(Api bot, UserSession session, string userName, string userPass)
 {
     if (session.Connection != null)
         session.Connection.Disconnect();
     else
         session.Connection = new Loodsman();
     try
     {
         session.Connection.Connect(userName, userPass);
         bot.SendTextMessage(session.UserId, "Подключение выполнено успешно");
     }
     catch (COMException)
     {
         bot.SendTextMessage(session.UserId, "Ошибка соединения с базой данных");
     }
 }
开发者ID:select-artur,项目名称:Telegram.Bot.Loodsman,代码行数:16,代码来源:Program.cs

示例3: CheckConnection

 private static bool CheckConnection(Api bot, UserSession session)
 {
     if (session.Connection == null)
         bot.SendTextMessage(session.UserId, "Выполните подключение к базе данных");
     else
         return true;
     return false;
 }
开发者ID:select-artur,项目名称:Telegram.Bot.Loodsman,代码行数:8,代码来源:Program.cs

示例4: DisconnectTask

 private static void DisconnectTask(Api bot, UserSession session)
 {
     if (CheckConnection(bot, session))
     {
         session.Connection.Disconnect();
         session.Connection = null;
         if (userSessions.ContainsKey(session.UserId))
             userSessions.Remove(session.UserId);
         bot.SendTextMessage(session.UserId, "Отключение соединения выполнено успешно");
     }
 }
开发者ID:select-artur,项目名称:Telegram.Bot.Loodsman,代码行数:11,代码来源:Program.cs

示例5: sendMessage

 public static bool sendMessage(int userId, string message)
 {
     try
     {
         var Bot = new Api("139410021:AAHoQsUYiH_NiHV0vutnDWSLy1JEslIibz0");
         Logging.logMessage(userId.ToString() + ' ' + message);
         Bot.SendTextMessage(userId, message);
         return true;
     }
     catch (Exception ex)
     {
         Logging.logMessage(ex.Message);
         return false;
     }
 }
开发者ID:arghand,项目名称:TelegramBot,代码行数:15,代码来源:TelegramBot.cs

示例6: Run

        static async Task Run()
        {
            var Bot = new Api("Your Api Key");

            var me = await Bot.GetMe();

            Console.WriteLine("Hello my name is {0}", me.Username);

            var offset = 0;

            while (true)
            {
                var updates = await Bot.GetUpdates(offset);

                foreach (var update in updates)
                {
                    if (update.Message.Type == MessageType.TextMessage)
                    {
                        await Bot.SendChatAction(update.Message.Chat.Id, ChatAction.Typing);
                        await Task.Delay(2000);
                        var t = await Bot.SendTextMessage(update.Message.Chat.Id, update.Message.Text);
                        Console.WriteLine("Echo Message: {0}", update.Message.Text);
                    }

                    if (update.Message.Type == MessageType.PhotoMessage)
                    {
                        var file = await Bot.GetFile(update.Message.Photo.LastOrDefault()?.FileId);

                        Console.WriteLine("Received Photo: {0}", file.FilePath);

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

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

                    offset = update.Id + 1;
                }

                await Task.Delay(1000);
            }
        }
开发者ID:carriercomm,项目名称:telegram.bot.examples,代码行数:44,代码来源:Program.cs

示例7: RunBot

        private static async Task RunBot()
        {
            InitGPIO(47);

            var Bot = new Api("Your API Key");

            var offset = 0;

            while (true)
            {
                var updates = await Bot.GetUpdates(offset);

                foreach (var update in updates)
                {
                    switch (update.Type)
                    {
                        case UpdateType.MessageUpdate:
                            var message = update.Message;

                            switch (message.Type)
                            {
                                case MessageType.TextMessage:

                                    if (message.Text == "/toggle")
                                    {
                                        ToggleLED();
                                        break;
                                    }

                                    await Bot.SendTextMessage(message.Chat.Id, message.Text,
                                        replyToMessageId: message.MessageId);

                                    break;
                            }
                            break;
                    }

                    offset = update.Id + 1;
                }
            }
        }
开发者ID:MrRoundRobin,项目名称:telegram.bot.examples,代码行数:41,代码来源:StartupTask.cs

示例8: Run

        static async Task Run()
        {
            var Bot = new Api(TokenUrl);

            var me = await Bot.GetMe();

            Console.WriteLine("Hello my name is {0}", me.Username);

            var offset = 0;

            while (true)
            {
                var updates = await Bot.GetUpdates(offset);

                foreach (var update in updates)
                {
                    if (update.Message.Type == MessageType.TextMessage)
                    {
                        await Bot.SendChatAction(update.Message.Chat.Id, ChatAction.Typing);
                        await Task.Delay(2000);

                        var splitMessage = update.Message.Text.Trim().Split(' ');

                        if (splitMessage.Length != 0 && splitMessage[0] == "budget")
                        {
                            try
                            {
                                float newBudget = float.Parse(splitMessage[1]);
                                budget = newBudget;
                                //redis.Set("budget", newBudget);
                            }
                            catch (Exception e)
                            {
                                Exception ex = e;
                            }
                        }
                        else if (splitMessage.Length != 0 && splitMessage[0] == "list")
                        {
                            var filterUser = splitMessage.Length == 2 ? splitMessage[1].Trim() : string.Empty;
                            
                            var outputString = new System.Text.StringBuilder();
                            if(s_expenses.Count == 0)
                            {
                                var tEmpty = await Bot.SendTextMessage(update.Message.Chat.Id, "No expenses recorded.");
                            }
                            else
                            {
                                foreach (var item in s_expenses)
                                {
                                    if(string.IsNullOrEmpty(filterUser) || item.User == filterUser)
                                    {
                                        var reply = string.Format("{0}: £{1} - ({2})", item.Timestamp.ToShortDateString(), item.Cost, item.Category);
                                        outputString.AppendLine(reply);
                                    }                                    
                                }

                                var t = await Bot.SendTextMessage(update.Message.Chat.Id, outputString.ToString());
                            }                            
                        }
                        else
                        {
                            try
                            {
                                var item = BudgetItem.Parse(update.Message.From.FirstName, update.Message.Text, DateTime.Now);
                                s_expenses.Add(item);
                                
                                budget -= item.Cost;
                            }
                            catch
                            {
                                var failResponse = await Bot.SendTextMessage(update.Message.Chat.Id, "Bad entry.  Try again.");
                                Console.WriteLine("Echo Message: {0}", failResponse);
                            }

                            var reply = string.Format("Budget: £{0}", budget);
                            var t = await Bot.SendTextMessage(update.Message.Chat.Id, reply);
                            Console.WriteLine("Echo Message: {0}", update.Message.Text);
                        }                        
                    }

                    if (update.Message.Type == MessageType.PhotoMessage)
                    {
                        var file = await Bot.GetFile(update.Message.Photo.LastOrDefault()?.FileId);

                        Console.WriteLine("Received Photo: {0}", file.FilePath);

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

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

                    offset = update.Id + 1;
                }

                await Task.Delay(1000);
            }
        }
开发者ID:mohammaddabiri,项目名称:BudgetBot,代码行数:100,代码来源:Program.cs

示例9: ProjectsTask

 private static void ProjectsTask(Api bot, UserSession session)
 {
     if (CheckConnection(bot, session))
     {
         try
         {
             var rootObj = session.Connection.ProjectList();
             bot.SendTextMessage(session.UserId, "Список проектов:" + Environment.NewLine
                 + rootObj.Childs.ToStringEx());
             session.CurrentObject = rootObj;
         }
         catch (COMException)
         {
             bot.SendTextMessage(session.UserId, "Ошибка при получении списка проектов");
         }
     }
 }
开发者ID:select-artur,项目名称:Telegram.Bot.Loodsman,代码行数:17,代码来源:Program.cs

示例10: Run

        private static async Task Run()
        {
            if (!String.IsNullOrEmpty(Properties.Settings.Default.ProxyUser))
            {
                var proxyCreds = new NetworkCredential(
                    Properties.Settings.Default.ProxyUser,
                    Properties.Settings.Default.ProxyPassword
                );

                WebRequest.DefaultWebProxy.Credentials = proxyCreds;
            }

            var bot = new Api(Properties.Settings.Default.BotToken);
            var me = await bot.GetMe();

            Console.WriteLine("Hello my name is {0}", me.FirstName);

            var offset = 0;

            while (true)
            {
                var updates = await bot.GetUpdates(offset);

                foreach (var update in updates)
                {
                    if (update.Message.Text != null
                        && update.Message.From.Id > 0
                        // Только приватные чаты
                        && update.Message.From.Id == update.Message.Chat.Id)
                    {
                        var session = GetUserSession(update.Message.From.Id);
                        if (update.Message.Text == "/connect")
                        {
                            session.LastCommand = update.Message.Text;
                            await bot.SendTextMessage(session.UserId, "Введите имя пользователя и его пароль в две строки");
                        }
                        else if (update.Message.Text == "/disconnect")
                        {
                            SetTask(session, () => DisconnectTask(bot, session));
                            session.LastCommand = "";
                        }
                        else if (update.Message.Text == "/projects")
                        {
                            SetTask(session, () => ProjectsTask(bot, session));
                            session.LastCommand = "";
                        }
                        else if (update.Message.Text == "/object")
                        {
                            SetTask(session, () => ObjectTask(bot, session));                            
                            session.LastCommand = update.Message.Text;
                        }
                        else if (update.Message.Text == "/file")
                        {
                            SetTask(session, () => FileTask(bot, session));
                            session.LastCommand = update.Message.Text;
                        }
                        else if (update.Message.Text == "/subscribe")
                        {
                            session.LastCommand = "";
                        }
                        else if (update.Message.Text == "/start" || update.Message.Text == "/help")
                        {
                            session.LastCommand = "";
                        }
                        else if (session.LastCommand == "/connect")
                        {
                            var cred = update.Message.Text.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
                            if (cred.Count() != 2)
                                await bot.SendTextMessage(session.UserId, "Введите имя пользователя и его пароль в две строки");
                            else
                            {
                                SetTask(session, () => ConnectTask(bot, session, cred[0], cred[1]));
                                session.LastCommand = "";
                            }
                        }
                        else if (session.LastCommand == "/object")
                        {
                            SetTask(session, () => ObjectTask(bot, session, update.Message.Text));
                            session.LastCommand = "";
                        }
                        else if (session.LastCommand == "/file")
                        {
                            SetTask(session, () => FileTask(bot, session, update.Message.Text));
                            session.LastCommand = "";
                        }
                        else
                        {
                            session.LastCommand = "";
                            await bot.SendTextMessage(session.UserId, "Неизвестная команда");
                        }
                    }

                    offset = update.Id + 1;
                }

                await Task.Delay(1000);
            }
        }
开发者ID:select-artur,项目名称:Telegram.Bot.Loodsman,代码行数:98,代码来源:Program.cs

示例11: FileTask

 private static void FileTask(Api bot, UserSession session, string fileName)
 {
     if (CheckConnection(bot, session))
     {
         if (session.CurrentObject == null)
             bot.SendTextMessage(session.UserId, "Не выбран объект");
         else
         {
             var file = session.CurrentObject.Files.Find(f => f.Name.Equals(fileName, StringComparison.InvariantCultureIgnoreCase));
             if (file == null)
                 bot.SendTextMessage(session.UserId, "Файл не найден");
             else
                 try
                 {
                     var fileFullName = session.Connection.GetFile(session.CurrentObject, file);
                     var ext = Path.GetExtension(fileName);
                     using (FileStream fs = new FileStream(fileFullName, FileMode.Open, FileAccess.Read))
                     {
                         Task<Message> task;
                         // Отправим фото
                         if (new[] { ".jpg", ".jpeg", ".gif", ".tif", ".bmp" }.Contains(ext))
                             task = bot.SendPhoto(session.UserId, new FileToSend(fileName, fs),
                                 fileName, 0, new ReplyKeyboardHide() { HideKeyboard = true });
                         else
                             task = bot.SendDocument(session.UserId, new FileToSend(fileName, fs),
                                 0, new ReplyKeyboardHide() { HideKeyboard = true });
                         task.Wait();
                     }
                 }
                 catch (COMException)
                 {
                     bot.SendTextMessage(session.UserId, "Ошибка при получении файла",
                         false, 0, new ReplyKeyboardHide() { HideKeyboard = true });
                 }
         }
     }
 }
开发者ID:select-artur,项目名称:Telegram.Bot.Loodsman,代码行数:37,代码来源:Program.cs

示例12: ObjectTask

        private static void ObjectTask(Api bot, UserSession session, string objProduct)
        {
            if (CheckConnection(bot, session) && session.CurrentObject != null)
            {
                try
                {
                    var obj = session.CurrentObject.Childs.Find(o => o.Product.Equals(objProduct, StringComparison.InvariantCultureIgnoreCase));
                    if (obj == null)
                        bot.SendTextMessage(session.UserId, "Объект не найден");
                    else
                    {
                        session.CurrentObject = obj;

                        var attrs = session.Connection.Attributes(obj);
                        if (attrs.Count() > 0)
                            bot.SendTextMessage(session.UserId, "Атрибуты объекта:" + Environment.NewLine
                                + string.Join(Environment.NewLine, attrs), false, 0, new ReplyKeyboardHide() { HideKeyboard = true });

                        session.Connection.FileList(obj);
                        if (obj.Files.Count > 0)
                            bot.SendTextMessage(session.UserId, "Файлы объекта:" + Environment.NewLine
                                + obj.Files.ToStringEx(), false, 0, new ReplyKeyboardHide() { HideKeyboard = true });

                        if (attrs.Count() == 0 && obj.Files.Count == 0)
                            bot.SendTextMessage(session.UserId, "У объекта нет атрибутов и файлов",
                                false, 0, new ReplyKeyboardHide() { HideKeyboard = true });
                    }
                }
                catch (COMException)
                {
                    bot.SendTextMessage(session.UserId, "Ошибка при получении информации об объекте",
                        false, 0, new ReplyKeyboardHide() { HideKeyboard = true });
                }
            }
        }
开发者ID:select-artur,项目名称:Telegram.Bot.Loodsman,代码行数:35,代码来源:Program.cs


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