static async Task Run() { var bot = new Api("113136707:AAE9Fh8p4SztOqmTzmNJDDE0rO_5WfhhYao"); var me = await bot.GetMe(); Console.WriteLine("Hello my name is {0}", me.Username); var offset = 0; Dictionary<string, CommandAbstract> commands = new Dictionary<string, CommandAbstract>(); WeatherCommand weather = new WeatherCommand(new OpenWeatherMap()); weather.AddWeatherAPI("ow", new OpenWeatherMap()); weather.AddWeatherAPI("yahoo", new YahooWeather()); commands.Add("/weather", weather); RateCommand rate = new RateCommand(new YahooRate()); commands.Add("/rate", rate); ArtificialIntelligenceCommand ai = new ArtificialIntelligenceCommand(); commands.Add("/ai", ai); while (true) { var updates = await bot.GetUpdates(offset); foreach (var update in updates) { if (update.Message.Type == MessageType.TextMessage) { var inputMessage = update.Message.Text; var messageParts = inputMessage.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); try { CommandAbstract command; if (!commands.TryGetValue(messageParts[0], out command)) command = weather; //default command (will be Echo) command.Execute(bot, messageParts, update); } catch (Exception ex) { Console.WriteLine(ex); } } offset = update.Id + 1; } await Task.Delay(1000); } }
private static async Task Run() { Api bot = new Api("146368700:AAEPKl3D6RLUNylmTqOUB-9cxKIwZGUyEfM"); int offset = 0; AiCommand aiCommand = new AiCommand(bot); CurrencyCommand currencyCommand = new CurrencyCommand(bot); DefaultCommand defaultCommand = new DefaultCommand(bot); WeatherCommand weatherCommand = new WeatherCommand(bot); TaskAddCommand taskAddCommand=new TaskAddCommand(bot); TaskListCommand taskListCommand = new TaskListCommand(bot); IBotCommand[] commands = {currencyCommand, weatherCommand,taskListCommand,taskAddCommand, aiCommand, defaultCommand}; while (true) { Update[] updates = await bot.GetUpdates(offset); foreach (Update update in updates) { if (update.Message.Type == MessageType.TextMessage) { string inputMessage = update.Message.Text; List<CommandEntity> commandsRecieved = MessageParser.ParseMessage(inputMessage); foreach (CommandEntity commandRecieved in commandsRecieved) { foreach (IBotCommand command in commands) { if (command.IsExecutable(commandRecieved.Name)) { Dictionary<string, object> context = new Dictionary<string, object> { {"commandEntity", commandRecieved}, {"update", update} }; command.Execute(context); break; } } } } offset = update.Id + 1; } await Task.Delay(1000); } }
public async Task Run() { var bot = new Telegram.Bot.Api("118916122:AAG24fT0i8fr6Cp9nXDdloRWXXA0Pbk0guM"); var me = await bot.GetMe(); Console.WriteLine("Bot {0} Initialized", me.Username); var offset = 0; while (true) { var updates = await bot.GetUpdates(offset); foreach (var update in updates) { if (update.Message.Text != null) { string messageText = update.Message.Text; try { if (messageText.Remove(0, 1).Substring(0, 4) == "IBot") { string reply = CommandInterpreter(messageText); await bot.SendTextMessage(update.Message.Chat.Id, reply); Console.WriteLine("Message recieved: '{0}'", update.Message.Text); Console.WriteLine("Message sent: '{0}'", reply); } // No else because the IF loop only applies to /IBot commands } catch (System.AggregateException) { // Not a valid command, ignore it } } offset = update.Id + 1; } await Task.Delay(1000); } }
static async Task Run() { var Bot = new Api(ConfigurationManager.AppSettings ["telegramAccessToken"]); 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); } offset = update.Id + 1; } await Task.Delay(1000); } }
/// <summary> /// Получаем бота, а если он еще /// не инициализирован - инициализируем /// и возвращаем /// </summary> public static Api Get() { if (_bot != null) return _bot; _bot = new Api(Config.BotApiKey); _bot.SetWebhook(Config.WebHookUrl); return _bot; }
public ShakalBot(string token) { Token = token; Api = new Api(token); Logic = new TelegramLogic<ShakalSession>(); }
protected override void InitRoutine() { _api = new Api(GetConfigString("ApiKey")); ChatId = GetConfigInteger("ForwardChatId"); Log.Add(LogLevel.Debug, "Telegram", "Initialising with bot key " + _api); }
public GuidBot() { var token = ConfigurationManager.AppSettings["apiToken"]; _bot = new Api(token); _state = BotState.Stopped; _offset = 0; }
static void Main(string[] args) { string apiKey = String.Empty; OptionSet set = new OptionSet { {"k|key=", "Telegram Bot {API-Key}", s => apiKey = s} }; set.Parse(args); if (apiKey == String.Empty) { Console.WriteLine("Telegram Bot Debug Tool"); Console.WriteLine("By Merlin Steuer in 2015"); Console.WriteLine(); Console.WriteLine("Usage:"); set.WriteOptionDescriptions(Console.Out); } else { Console.WriteLine("Using API-Key {0}", apiKey); Console.WriteLine(); Api telegram = new Api(apiKey); User me = telegram.GetMe().Result; int offset = 0; Console.WriteLine("Logged in as"); Console.WriteLine("User {0} ({1})", me.Username, me.Id); Console.WriteLine("Full {0} {1}", me.FirstName, me.LastName); Console.WriteLine(); Console.WriteLine("Receiving Text-Messages..."); while (true) { Update[] updates = telegram.GetUpdates(offset).Result; foreach (Update update in updates) { if (update.Message.Type == MessageType.TextMessage) { Console.WriteLine("TextMessage received:"); Console.WriteLine("Chat ID: {0}", update.Message.Chat.Id); Console.WriteLine("From: {0} {1} / {2}", update.Message.From.FirstName, update.Message.From.LastName, update.Message.From.Username); Console.WriteLine("Message: {0}", update.Message.Text); Console.WriteLine(); } offset = update.Id + 1; } Thread.Sleep(1000); } } }
public static Api Get() { if (_bot != null) return _bot; _bot = new Api(Config.BotApiKey); _bot.SetWebhook(Config.WebHookUrl); if (Config.BotAdmins.Any()) StartedAtUtc = _bot.SendTextMessage(Config.BotAdmins.First(), "I'm initialized and ready for work!").Result.Date.ToUniversalTime(); return _bot; }
public override void Execute(Api bot, string[] messageParts, Update update) { string message = string.Empty; string[] changedMessageParts = new string[messageParts.Length]; CorrectMisprintsInWords(messageParts, changedMessageParts); message = AnalyzeMessage(changedMessageParts); var t = bot.SendTextMessage(update.Message.Chat.Id, message); Console.WriteLine("Echo Message: {0}", message); }
public virtual void HandleMessage(Api api, Message message, object state) { var chatId = message.Chat.Id; TelegramSession session; if (!Sessions.TryGetValue(chatId, out session)) { session = CreateSession(); Sessions[chatId] = session; } session.HandleMessage(api, message, state); }
public void Execute(Api bot, string[] currencies, Update update) { string url = string.Format(@"https://query.yahooapis.com/v1/public/yql?q=env 'store://datatables.org/alltableswithkeys'; select * from yahoo.finance.xchange where pair='{0}'&format=json", currencies[1] + currencies[2]); string responseString = new ResponseService().GetResponse(url); Console.WriteLine(responseString); var rateResponse = JsonConvert.DeserializeObject<RateResponse>(responseString); var message = "1 " + currencies[1] + " = " + rateResponse.query.results.rate.Rate + currencies[2]; var t = bot.SendTextMessage(update.Message.Chat.Id, message); Console.WriteLine("Echo Message: {0}", message); }
public DwellerBot() { _rng = new Random(); // Get bot api token _bot = new Api(""); Offset = 0; CommandsProcessed = 0; ErrorCount = 0; LaunchTime = DateTime.Now.AddHours(3); Commands = new Dictionary<string, ICommand> { {@"/rate", new RateNbrbCommand(_bot)}, }; }
public ReactionCommand(Api bot, List<string> folderNames, string cacheFilePath):base(bot) { _rng = new Random(); _files = new List<FileInfo>(); foreach (var folderName in folderNames) { var dir = new DirectoryInfo(folderName); if (dir.Exists) { _files.AddRange(dir.EnumerateFiles().ToList()); } } _cacheFilePath = cacheFilePath; // Since Telegram allows you to "send" files by using their id (if they are on the server already), // I use this to create a simple cache by sending id of a file if it was already sent once. _sentFiles = new Dictionary<string, string>(); }
static void InitCommandContainer(CommandContainer CommandContainer, Api bot) { CommandContainer.RegistreCommand("/weather" , new WeatherCommand<WeatherMetricsContainer>(bot , new WeatherService(new OpenWeatherMapRepository()) , new WeatherArgumentsParser("Minsk") , new WeatherMessageBuider() ) ); CommandContainer.RegistreCommand("/rate" , new RateCommand<CurrencyInfo>(bot , new RateService(new YahooapisRateRepository()) , new RateArgumentsParser() , new RateMessageBuilder() ) ); }
static async Task Run() { api = new Api(token); var bot = await api.GetMe(); WriteLine($"Bot: {bot.Username}"); var offset = 0; while (true) { Enumerable.Range(0, 4).ToList().ForEach(x => WriteLine("")); WriteLine("Getting updates!"); var updates = await api.GetUpdates(offset); updates.ToList().ForEach(up => TratarUpdate(up, ref offset)); WriteLine("Waiting!"); await Task.Delay(2000); } }
public AskStasonCommand(Api bot, string responsesFilePath):base(bot) { _rng = new Random(); _responses = new List<string>(); _weights = new List<int>(); using (var sr = new StreamReader(new FileStream(responsesFilePath, FileMode.Open))) { var str = sr.ReadToEnd(); if (str.Length > 0) { Dictionary<string, int> config = null; try { config = JsonConvert.DeserializeObject<Dictionary<string, int>>(str); } catch (Exception ex) { Log.Logger.Error("An error as occured during parsing of {0} file. Error message: {1}", responsesFilePath, ex.Message); } if (config != null) { // { a:5, b:5, c:3, d:1 } => { 5:a, 10:b, 13:c, 14:d } int accumulator = 0; foreach (var item in config) { // Skip incorrect values if (item.Value < 0) continue; accumulator += item.Value; _responses.Add(item.Key); _weights.Add(accumulator); } _maxRadnomValue = accumulator; } } else { Log.Logger.Warning("The file {0} was expected to be populated with data, but was empty.", responsesFilePath); } } }
public virtual void HandleMessage(Api api, Message message, object state) { if (message.Type == MessageType.TextMessage) { var text = message.Text.Trim(); if (text == "/start") { StartHandler.HandleMessage(this, api, message, state); return; } else if (text == "/help") { HelpHandler.HandleMessage(this, api, message, state); return; } } var handler = CurrentHandler; var next = handler.HandleMessage(this, api, message, state); CurrentHandler = next; }
static async Task Run() { ILogger logger = LogManager.GetLogger("WeatherLogger"); var bot = new Api("153673700:AAEGCovvWRm_m86KSSGQrw3RTbczdixZ12Y"); var me = await bot.GetMe(); CommandManager manager = new CommandManager(new DefaultCommand(logger)); manager.AddCommand("/weather", new WeatherCommand(logger)); var welcomeString = string.Format("Hello my name is {0}", me.Username); logger.Info(welcomeString); Console.WriteLine(welcomeString); var offset = 0; while (true) { var updates = await bot.GetUpdates(offset); foreach (var update in updates) { var context = new Dictionary<string, object>() { {"bot", bot}, {"update", update} }; var command = manager.GetCommand(update.Message.Text); if (command.IsApplicable(context)) { command.Execute(context); } offset = update.Id + 1; } await Task.Delay(1000); } }
public override void Execute(Api bot, string[] messageParts, Update update) { IWeather weather = null; string city = defaultCity; if (messageParts.Length > 1) { if (!handlers.TryGetValue(messageParts[1], out weather)) city = messageParts[1]; else city = messageParts.Length > 2 ? messageParts[2] : defaultCity; } weather = weather ?? defaultWeather; Models.Weather weatherResponse = weather.GetWeatherByCity(city); var message = "In " + weatherResponse.City + " " + weatherResponse.Description + " and the temperature is " + weatherResponse.Tempearature + "°C"; var t = bot.SendTextMessage(update.Message.Chat.Id, message); Console.WriteLine("Echo Message: {0}", message); }
static async Task Run() { var bot = new Api("145582668:AAEmRBxWzopyLmjniOw3SCshn1gdL4JcZEw"); var me = await bot.GetMe(); Console.WriteLine("Hello my name is {0}", me.Username); var offset = 0; var commandContainer = new CommandContainer(new DefaultCommand(bot)); InitCommandContainer(commandContainer, bot); while (true) { var updates = await bot.GetUpdates(offset); foreach (var update in updates) { if (update.Message.Type == MessageType.TextMessage) { var inputParser = new InputMessageParser(); var inputMessage = inputParser.Parse(update.Message.Text); var command = commandContainer.GetCommand(inputMessage.Command); var context = new Dictionary<string, object> { {"argumentsString", inputMessage.Arguments}, {"update", update} }; await command.ExecuteAsync(context); //await command.ExecuteAsync(inputMessage.Arguments, update); // всегда выполняется дефолтное действие // получится ли с помощью такого контекста все выполнять в цикле } offset = update.Id + 1; } await Task.Delay(1000); } }
public DwellerBot(Settings settings) { // move to container CommandService = new CommandService(BotName); _rng = new Random(); // Get bot api token _bot = new Api(settings.keys.First(x => x.name == "dwellerBotKey").value); Offset = 0; CommandsProcessed = 0; ErrorCount = 0; LaunchTime = DateTime.Now.AddHours(3); CommandService.RegisterCommands(new Dictionary<string, ICommand> { {@"/debug", new DebugCommand(_bot, this)}, {@"/rate", new RateNbrbCommand(_bot)}, {@"/askstason", new AskStasonCommand(_bot, settings.paths.paths.First(x => x.name == "askStasonResponsesPath").value)}, {@"/weather", new WeatherCommand(_bot, settings.keys.First(x => x.name == "openWeatherKey").value)}, { @"/reaction", new ReactionCommand( _bot, settings.paths.pathGroups.First(x => x.name == "reactionImagePaths").paths.Select(x => x.value).ToList(), settings.paths.paths.First(x => x.name == "reactionImageCachePath").value ) }, {@"/rtd", new RtdCommand(_bot)}, {@"/featurerequest", new FeatureRequestCommand(_bot, settings.paths.paths.First(x => x.name == "featureRequestsPath").value)}, {@"/bash", new BashimCommand(_bot)}, {@"/savestate", new SaveStateCommand(_bot, this)}, {@"/shutdown", new ShutdownCommand(_bot, this)} }); CommandService.LoadCommandStates(); }
static async Task Run() { Api bot = new Api("153673700:AAEGCovvWRm_m86KSSGQrw3RTbczdixZ12Y"); var me = await bot.GetMe(); ILogger logger = LogManager.GetLogger("RateLogger"); var welcomeString = string.Format("Hello my name is {0}", me.Username); logger.Info(welcomeString); Console.WriteLine(welcomeString); RateService service = new RateService(logger); ICommand command = new RateCommand(logger, service); var offset = 0; while (true) { var updates = await bot.GetUpdates(offset); foreach (var update in updates) { var context = new RateContext() { Update = update, Bot = bot }; command.Execute(context); offset = update.Id + 1; } await Task.Delay(1000); } }
public SaveStateCommand(Api bot, DwellerBot dwellerBot):base(bot) { _dwellerBot = dwellerBot; }
public abstract void Execute(Api bot, string[] messageParts, Update update);
public CustomBot(string apiKey) { api = new Api(apiKey); }
public DefaultCommand(Api bot) { this._bot = bot; }
public BotApiService(string token) { if (string.IsNullOrEmpty(token)) throw new ArgumentException("Token é necessário, para a comunicação com a API."); _api = new Api(token); }
public CommandManager(Api bot, ConcurrentBag<ICommand> commands) { commandDictionary = commands; this.bot = bot; }
public async Task RunBot() { Bot = new Telegram.Bot.Api(Token); me = await Bot.GetMe(); Translator.Translator T = null; Console.WriteLine("System>{0} is on!", me.Username); int offset = 0; while (true) { Update[] updates = await Bot.GetUpdates(offset); foreach (Update update in updates) { this.update = update; if (update.Message.From.Id.ToString() == user)//Auth OK { if (update.Message.Type == MessageType.TextMessage) { Console.WriteLine(update.Message.Text); if (update.Message.Text == "/start") { SendMessage("일본어 번역기 봇 ver" + Version + " by 조호연@KMOU"); SendMessage("일본어, 한국어, Romaji 지원"); offset = update.Id + 1; break; } try { T = new Translator.Translator(update.Message.Text); T.Translate(); switch (T.L.SoruceType) { case "ko": SendMessage("번역된 말 : " + T.L.Japanese + "\n\n재번역된 말 : " + T.L.Retranslated + "\n\n일본어 발음 : " + T.L.Furigana); SendMessage(T.L.Japanese); break; case "ja": SendMessage("번역된 말 : " + T.L.Korean + "\n\n재번역된 말 : " + T.L.Retranslated + "\n\n일본어 발음 : " + T.L.Furigana); break; case "rmj": SendMessage(T.L.Japanese + "으로 변경되었음.\n" + "번역된 말 : " + T.L.Korean + "\n\n재번역된 말 : " + T.L.Retranslated + "\n\n일본어 발음 : " + T.L.Furigana); break; default: SendMessage("해석 불가!"); break; } T = null; } catch (Exception e) { SendMessage("Error!"); offset = update.Id + 1; continue; } } offset = update.Id + 1; } } await Task.Delay(500); } }