public static ITelegramBotClient Get() { if (botclient != null) { return(botclient); } commandlist = new List <Command> { new StartCommand(), new SecretWord() }; handlerLists = new List <Handler> { new TextHandler() }; botclient = new TelegramBotClient(AppSettings.BotToken); var me = botclient.GetMeAsync().Result; if (me != null) { botclient.StartReceiving(); return(botclient); } throw new Exception("Bot not started"); }
static void Main() { var proxy = new HttpToSocks5Proxy("191.101.148.34", 45786, "Selvzhukov1985", "D1d4WpP"); botClient = new TelegramBotClient("1097325383:AAGo_rsBVsL7s3kjihWSSEVb2XJYi-3sSd4", proxy); randNum = new Random(); deckCardsCount = new int[3]; deckCardsCount[0] = 130; deckCardsCount[1] = 130; deckCardsCount[2] = 130; deckCardsUsed = new ArrayList[3]; for (int i = 0; i < 3; i++) { deckCardsUsed[i] = new ArrayList(); } var me = botClient.GetMeAsync().Result; Console.WriteLine( $"Hello, World! I am user {me.Id} and my name is {me.FirstName}." ); botClient.OnMessage += Bot_OnMessage; botClient.StartReceiving(); Thread.Sleep(int.MaxValue); }
public void SetupGini(EventHandler <MessageEventArgs> OnMessageHandler = null) { if (botClient == null) { botClient = new TelegramBotClient(BotConfig.AccessToken); var me = botClient.GetMeAsync().Result; Console.WriteLine($"Hello, World! I am user {me.Id} and my name is {me.FirstName}."); if (OnMessageHandler == null) { handler = new GiniHandler(); botClient.OnMessage += GiniHandler.OnMessageWithApi; } else { botClient.OnMessage += OnMessageHandler; } } else { if (OnMessageHandler == null) { if (handler == null) { handler = new GiniHandler(); botClient.OnMessage += GiniHandler.OnMessageWithApi; } } else { botClient.OnMessage += OnMessageHandler; } } botClient.StartReceiving(); }
/// <inheritdoc /> public async Task <HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = new CancellationToken()) { try { var bot = await _client.GetMeAsync(cancellationToken); var data = new Dictionary <string, object> { ["bot.username"] = $"@{bot.Username}", ["bot.id"] = bot.Id, }; return(HealthCheckResult.Healthy(data: data)); } catch (Exception e) { var text = e is TaskCanceledException || e is HttpRequestException ? "Telegram connection could not be established" : "Telegram connection could not be established or bot authorization data is invalid."; var data = new Dictionary <string, object> { ["exception.type"] = e.GetType().Name, ["exception.message"] = e.Message }; return(HealthCheckResult.Unhealthy(text, e, data)); } }
public async Task StartAsync(CancellationToken cancellationToken) { var me = await _client.GetMeAsync(cancellationToken); _logger.Information("Started bot @{UserName}", me.Username); _client.StartReceiving(cancellationToken: cancellationToken); }
internal void GetUpdate() { _client = new TelegramBotClient(_token); var me = _client.GetMeAsync().Result; if (me != null && !string.IsNullOrEmpty(me.Username)) { int offset = 0; while (true) { try { var updates = _client.GetUpdatesAsync().Result; if (updates != null && updates.Count() > 0) { foreach (var update in updates) { processUpdate(update); offset = update.Id + 1; } } } catch (Exception ex) { Console.WriteLine(ex.Message); } Thread.Sleep(1000); } } }
public GetRequest(TelegramSettings settings, Notification notification) { _botClient = new TelegramBotClient(settings.Token) { Timeout = TimeSpan.FromSeconds(5) }; var me = _botClient.GetMeAsync().Result; foreach (var chatId in settings.ChatId) { Bot_SendMessage(chatId, notification); } _botClient.OnCallbackQuery += async(object sc, CallbackQueryEventArgs ev) => { var message = ev.CallbackQuery.Message; while (true) { if (ev.CallbackQuery.Data == "myCommand1") { // сюда то что тебе нужно сделать при нажатии на первую кнопку Console.WriteLine("Ура"); } else if (ev.CallbackQuery.Data == "myCommand2") { Console.WriteLine("Ура 2"); // сюда то что нужно сделать при нажатии на вторую кнопку } } }; }
static void Main(string[] args) { //Set config file #if DEBUG var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings_debug.json"); #else var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json"); #endif _config = builder.Build(); _shutUpCounter = 0; _shutUpTreshold = int.Parse(_config["shutUpThreshold"]); _shutUpCheckList = _config.GetSection("shutUpCheckList").GetChildren().Select(fm => fm.Value.ToString()).ToList(); _shutUpResponseList = _config.GetSection("shutUpResponseList").GetChildren().Select(fm => fm.Value.ToString()).ToList(); //Init bot client _botClient = new TelegramBotClient(_config["accessToken"]); _botUser = _botClient.GetMeAsync().Result; //Init db service _service = new WBotService(); _botClient.OnMessage += Bot_OnMessage; _botClient.StartReceiving(); Thread.Sleep(int.MaxValue); }
static void Main(string[] args) { bot = new TelegramBotClient("1244554441:AAHULJVSMUs-d0DTWaJaTtqmQ1nLggxjcGM") { Timeout = TimeSpan.FromSeconds(10) }; try { var me = bot.GetMeAsync().Result; Console.WriteLine($"Я бот {me.Id}, меня зовут {me.FirstName}"); bot.OnMessage += Bot_OnMessage; bot.OnCallbackQuery += BotOnCallbackQueeryRecived; bot.StartReceiving(); Console.ReadKey(); } catch { Console.WriteLine("Нет подключения к серверу"); Console.ReadKey(); } }
public async Task RunAsync() { ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("redis"); cache = redis.GetDatabase(); botClient = new TelegramBotClient(ConfigurationManager.AppSettings.Get("Token")) { Timeout = TimeSpan.FromSeconds(Int32.Parse(ConfigurationManager.AppSettings.Get("BotTimeout"))) }; var me = await botClient.GetMeAsync(); Console.WriteLine($"User {me.Id} - {me.FirstName} was launched at {DateTime.Now}."); botClient.OnMessage += Bot_OnMessage; botClient.StartReceiving(); Console.WriteLine("Press Ctrl + C to cancel!"); //CancelKey need to run docker without "tail -f /dev/null" parameter Console.CancelKeyPress += ((s, a) => { Console.WriteLine("Bye!"); _closingEvent.Set(); }); _closingEvent.WaitOne(); botClient.StopReceiving(); }
public static void Main(string[] args) { replyKeyboard = new[] { Texts.ACCEPT, Texts.CANCEL }; replyKeyboardRemove = new ReplyKeyboardRemove(); replyKeyboard.OneTimeKeyboard = true; replyKeyboard.ResizeKeyboard = true; botClient = new TelegramBotClient("---BOT API HERE---"); usersDictionary = new ConcurrentDictionary <long, User>(); var me = botClient.GetMeAsync().Result; Console.WriteLine("Connected: " + me.FirstName); botClient.OnMessage += Bot_OnMessage; botClient.StartReceiving(); while (true) { foreach (User user in usersDictionary.Values) { user.CheckFinishedBlock(); } } }
public async Task InitializeAsync() { _logger.LogInformation("initializing application..."); _logger.LogInformation("testing coinigy api connection..."); try { var accounts = await _coinigyApiClient.GetExchangeAccountsAsync(); foreach (var account in accounts) { _logger.LogInformation($"found coinigy exchange account {account.Name} with id {account.Id}"); } } catch (Exception e) { _logger.LogCritical(e, "unable to connect to coinigy, please verify your settings!"); throw; } _logger.LogInformation("testing telegram connection..."); try { var me = await _telegramBotClient.GetMeAsync(); _logger.LogInformation($"telegram connection successful. hello from {me.Username}!"); } catch (Exception e) { _logger.LogCritical(e, "unable to connect to telegram, please verify your settings!"); throw; } }
static void Main(string[] args) { dataBase = new DataBase(); usersDataBase = new UsersDataBase(); var proxy = new WebProxy(ip, port); proxy.Credentials = new NetworkCredential(); botClient = new TelegramBotClient(token, proxy); var me = botClient.GetMeAsync().Result; Console.WriteLine($"Hello, World! I am user {me.Id} and my name is {me.FirstName}"); botClient.OnMessage += Bot_OnMessage; // Когда приходит сообщение botClient.OnUpdate += Bot_OnUpdate; //Принимаемые сообщения botClient.StartReceiving(); Thread.Sleep(int.MaxValue); Console.ReadKey(); }
static void Main() { botClient = new TelegramBotClient("676101534:AAGQMTb_4eHW_VstJDnK60ps8hx6jsP9OD4"); Butin.Add("Для тех, кто не говорит по-русски... *шёпотом* А здесь такие есть"); Butin.Add("Так это, как это ваша фамилия?"); Butin.Add("Ясно, понятно."); Butin.Add("Достаточно"); Butin.Add("Один белый убил четырёх красных."); Strigalev.Add("Семантические связи, молодые люди."); Strigalev.Add("Я вам в тысячный раз повторяю, эпам вас обманывает."); Strigalev.Add("Есть правила игры и по ним нужно играть"); Protchenko.Add("Я пришла сюда работать не ради денег."); Protchenko.Add("Ну чё, сдаём или по домам?"); Protchenko.Add("Я вам покажу, как развернуть Докер-контейнер, когда-нибудь"); Protchenko.Add("Пойдёте лабы Гончаревичу сдвать"); Memas.Add("https://raw.githubusercontent.com/donwhispers/chatbotssp/master/mems/izGUdkA7itU.jpg"); Memas.Add("https://raw.githubusercontent.com/donwhispers/chatbotssp/master/mems/K0a0QHM67nk.jpg"); Memas.Add("https://raw.githubusercontent.com/donwhispers/chatbotssp/master/mems/cq0D4htFVOo.jpg"); Memas.Add("https://raw.githubusercontent.com/donwhispers/chatbotssp/master/mems/dpESvZRLMIE.jpg"); Memas.Add("https://raw.githubusercontent.com/donwhispers/chatbotssp/master/mems/fKEjfI5ajbE.jpg"); Memas.Add("https://raw.githubusercontent.com/donwhispers/chatbotssp/master/mems/bOb-Ji8DALk.jpg"); var me = botClient.GetMeAsync().Result; Console.WriteLine( $"Hello, World! I am user {me.Id} and my name is {me.FirstName}." ); botClient.OnMessage += Bot_OnMessage; botClient.StartReceiving(); Thread.Sleep(int.MaxValue); }
static void Main() { botClient = new TelegramBotClient( "728991596:AAGn5lcWrOVxVWDAVHy97ca_BhqXpocYRHQ", new SocksWebProxy( new ProxyConfig( IPAddress.Parse("127.0.0.1"), GetNextFreePort(), IPAddress.Parse("185.20.184.217"), 3693, ProxyConfig.SocksVersion.Five, "userid66n9", "pSnEA7M"), false) ); var me = botClient.GetMeAsync().Result; Console.WriteLine( $"Привет, юзер! Я {me.Id} и меня зовут {me.FirstName}. Напиши мне что-нибудь:)" ); botClient.OnMessage += Bot_OnMessage; botClient.StartReceiving(); Thread.Sleep(int.MaxValue);; }
static async Task Main(string[] args) { _rant.LoadPackage(@"F:\Downloads\Rantionary-master\Rantionary-master\build\Rantionary-3.1.0.rantpkg"); var proxy = new WebProxy { Address = new Uri("http://194.32.239.71:56380"), Credentials = new NetworkCredential { UserName = "******", Password = "******" } }; _client = new TelegramBotClient("1087063556:AAHG7tjOi-r_9auYr8vy7lFka1k1J1z9s_g", proxy); var me = await _client.GetMeAsync(); Console.WriteLine($"{me.Id} running..."); _client.OnMessage += OnMessage; _client.StartReceiving(); Thread.Sleep(int.MaxValue); }
public void Initialize() { IList <BotCommand> commands = new List <BotCommand>() { new BotCommand() { Command = BotCommands.Time, Description = "User local time", }, new BotCommand() { Command = BotCommands.Friend, Description = "Add friend to view your local time.", }, new BotCommand() { Command = BotCommands.FriendList, Description = "Display your friends list.", }, new BotCommand() { Command = BotCommands.Timezone, Description = "Set your timezone." } }; Bot = botClient.GetMeAsync() .GetAwaiter() .GetResult(); botClient.SetMyCommandsAsync(commands) .GetAwaiter() .GetResult(); botClient.OnMessage += HandlerMessageAsync; botClient.StartReceiving(); }
static void Main(string[] args) { _botClient = new TelegramBotClient(ApiKeys.TelegramApi); var me = _botClient.GetMeAsync().Result; Console.WriteLine( $"Hello, World! I am user {me.Id} and my name is {me.FirstName}." ); CurrentState.State = State.Default; _botClient.OnMessage += Bot_OnMessage; _botClient.StartReceiving(); GlobalConfiguration.Configuration.UseSqlServerStorage(ApiKeys.ConnectionString); using (var server = new BackgroundJobServer()) { BackgroundJob.Schedule(() => Console.WriteLine("Hello, world!"), TimeSpan.FromMinutes(1)); Console.WriteLine("Hangfire Server started. Press any key to exit..."); Console.ReadKey(); } Console.WriteLine("Press any key to exit"); Console.ReadKey(); _botClient.StopReceiving(); }
static void Main() { Console.CancelKeyPress += (sender, eArgs) => { quitEvent.Set(); eArgs.Cancel = true; }; var apiToken = Environment.GetEnvironmentVariable("TOTUUSBOTTI_API_TOKEN"); botClient = new TelegramBotClient(apiToken); var me = botClient.GetMeAsync().Result; Console.WriteLine( $"Hello, World! I am user {me.Id} and my name is {me.FirstName}." ); botClient.OnMessage += Bot_OnMessage; botClient.StartReceiving(); Console.WriteLine("Press Ctrl+C to exit"); redditBot = new RedditBot(); #if (ENABLE_REDDITBOT) redditBot.Configure(); #endif // Keep program alive until STOP-signal quitEvent.WaitOne(); botClient.StopReceiving(); }
static void Main(string[] args) { DirtyLittleSecretsMap items; string projectFolder = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory()))); using (StreamReader r = new StreamReader(Path.Combine(projectFolder, "DirtyLittleSecrets.json"))) { string json = r.ReadToEnd(); items = JsonConvert.DeserializeObject <DirtyLittleSecretsMap>(json); } botClient = new TelegramBotClient(items.BotToken); var me = botClient.GetMeAsync().Result; Console.WriteLine( $"Hello, World! I am user {me.Id} and my name is {me.FirstName}." ); botClient.OnUpdate += Bot_OnUpdate; botClient.OnMessage += Bot_OnMessage; botClient.StartReceiving(); Thread.Sleep(int.MaxValue); }
public MainBot() { if (AppSettings.isDevEnvironment) { ICredentials cread = new NetworkCredential(AppSettings.proxyLogin, AppSettings.proxyPassword); WebProxy proxy = new WebProxy(AppSettings.proxyAddress, false, null, cread); mainbot = new TelegramBotClient(AppSettings.mainKey, proxy); } else { mainbot = new TelegramBotClient(AppSettings.mainKey); } User me = mainbot.GetMeAsync().Result; Console.WriteLine($"Hello, World! I am user №{me.Id}, alias {me.Username} and my name is {me.FirstName}."); mainbot.OnMessage += Bot_OnMessage; //TODO: Добавить сохранение отправленных картинок. прост по приколу mainbot.OnCallbackQuery += Bot_OnCallbackQuery; mainbot.OnReceiveError += Bot_OnError; mainbot.StartReceiving(); //Этот процесс нужен для мониторинга жизнеспособности бота. Нет сообщений - бот отвалился. Thread countThread = new Thread(new ThreadStart(Count)); countThread.Start(); }
public void Start() { var user = _telegramBotClient.GetMeAsync().Result; _telegramBotClient.OnMessage += OnMessage; _telegramBotClient.StartReceiving(); }
public void Start() { _startDate = DateTime.UtcNow; _logger.LogInformation("Starting Telegram Bot"); _telegramBotClient.OnMessage += BotOnMessageReceived; _telegramBotClient.OnMessageEdited += BotOnMessageReceived; //_telegramBotClient.OnCallbackQuery += BotOnCallbackQueryReceived; //_telegramBotClient.OnInlineQuery += BotOnInlineQueryReceived; //_telegramBotClient.OnInlineResultChosen += BotOnChosenInlineResultReceived; //_telegramBotClient.OnReceiveError += BotOnReceiveError; var me = _telegramBotClient.GetMeAsync().Result; Console.Title = me.Username; _logger.LogInformation($"Telegram Bot testing connection => {me.Username}"); _coinMarketCapClient = new CoinMarketCapClient(); _telegramBotClient.StartReceiving(); _started = true; _logger.LogInformation("Telegram Bot started"); }
static void Main(string[] args) { MebelRuBotContext.Init(); employeeManager = new EmployeeManager(); //var proxy = new HttpToSocks5Proxy("103.194.171.156", 8888); //proxy.ResolveHostnamesLocally = true; //botClient = new TelegramBotClient("755174490:AAGr0dyLPskL3UL3HyUeJbqXVXpijKj7hCI", proxy) { botClient = new TelegramBotClient("755174490:AAGr0dyLPskL3UL3HyUeJbqXVXpijKj7hCI") { Timeout = TimeSpan.FromSeconds(10) }; //users.Add(BORIS_ID, new Admin(botClient, BORIS_ID)); employeeManager.Add(new Admin() { Id = BORIS_ID }); var me = botClient.GetMeAsync().Result; Console.WriteLine($"Bot Id: {me.Id}. Bot Name: {me.FirstName}"); botClient.OnMessage += BotClient_OnMessage; botClient.StartReceiving(); Console.ReadKey(); }
static void Main() { botClient = new TelegramBotClient( "778568242:AAFAuMifVwnWFQOPB4fjymPNJ4Wy6ukBRrk", new SocksWebProxy( new ProxyConfig( IPAddress.Parse("127.0.0.1"), GetNextFreePort(), IPAddress.Parse("185.20.184.217"), 3693, ProxyConfig.SocksVersion.Five, "userid66n9", "pSnEA7M"), false) ); var me = botClient.GetMeAsync().Result; Console.WriteLine( $"Привет, юзер! Я {me.Id} и меня зовут {me.FirstName}. Напиши мне что-нибудь:)" ); botClient.OnMessage += Bot_OnMessage; botClient.StartReceiving(); Thread.Sleep(int.MaxValue); }
//static ApiAi apiAi; static void Main(string[] args) { botClient = new TelegramBotClient("1227072027:AAGGhpJp7UvgEzrVuFq4Msof92rFHHaOTk4") { Timeout = TimeSpan.FromSeconds(10) }; //подключение к АПИ и разгрузка сервера //AIConfiguration config = new AIConfiguration("dc83c0406e75c7e2fc004e4781167f1c42134024", SupportedLanguage.Russian); //apiAi = new ApiAi(config); try { var me = botClient.GetMeAsync().Result; //Получение данных о боте Console.WriteLine($"Bot id: {me.Id}. Bot name is {me.FirstName}"); //подключен ли бот и как его зовут botClient.OnMessage += Bot_OnMessage; //подписались на получение сообщения botClient.OnCallbackQuery += BotOnCallbackQueryRecived; //подключили обработку действий с кнопок botClient.StartReceiving(); //ожидание новых сообщений Console.ReadKey(); //консоль не будет закрываться))) } catch { Console.WriteLine("Отсутствует побключение"); } }
public static async Task Main(string[] args) { string botId = Environment.GetEnvironmentVariable("BOT_ID"); if (String.IsNullOrEmpty(botId)) { throw new InvalidOperationException("Need BOT_ID with bot id"); } botClient = new TelegramBotClient(botId); var me = await botClient.GetMeAsync(); Console.Title = me.Username; var cts = new CancellationTokenSource(); // StartReceiving does not block the caller thread. Receiving is done on the ThreadPool. botClient.StartReceiving( new DefaultUpdateHandler(HandleUpdateAsync, HandleErrorAsync), cts.Token ); Console.WriteLine($"Start listening for @{me.Username}"); Console.ReadLine(); // Send cancellation request to stop bot cts.Cancel(); }
static void Main() { botClient = new TelegramBotClient(""); data = new DataRepo(""); keyboards = new Keyboards(data, data.GetCurrentEvents()); Console.WriteLine("Starting..."); var me = botClient.GetMeAsync().Result; Console.WriteLine( $"Hello, World! I am user {me.Id} and my name is {me.FirstName}." ); botClient.OnMessage += Bot_OnMessage; botClient.OnCallbackQuery += BotClient_OnCallbackQuery; botClient.StartReceiving(); Console.WriteLine("Press any key to exit"); //Console.ReadKey(); while (true) { } botClient.StopReceiving(); }
//private readonly static HttpToSocks5Proxy proxy = new HttpToSocks5Proxy("96.96.33.133", 1080); static void Main(string[] args) { //bot = new TelegramBotClient(token, proxy) { Timeout = TimeSpan.FromSeconds(10) }; bot = new TelegramBotClient(token) { Timeout = TimeSpan.FromSeconds(10) }; try { var me = bot.GetMeAsync().Result; Console.WriteLine($"Bot connected id: {me.Id}. Bot name: {me.FirstName}"); } catch (Exception) { Console.WriteLine("Time Out"); return; } bot.OnMessage += OnMessageHandler; bot.OnCallbackQuery += OnCallbackQueryHandler; // Saving records every 30 sec ThreadPool.QueueUserWorkItem(Save); // updating records ThreadPool.QueueUserWorkItem(MidnightUpdate, bot); // Sending notifications ThreadPool.QueueUserWorkItem(planner.Notify, bot); bot.StartReceiving(); Console.ReadKey(); }
public static void Initialize(string apikey) { if (CacheData.FatalError) { return; } if (String.IsNullOrEmpty(apikey)) { Data.Utils.Logging.AddLog(new Models.SystemLog() { LoggerName = CacheData.LoggerName, Date = DateTime.Now, Function = "Unifiedban Terminal Startup", Level = Models.SystemLog.Levels.Fatal, Message = "API KEY must be set!", UserId = -1 }); CacheData.FatalError = true; return; } APIKEY = apikey; instanceId = Guid.NewGuid().ToString(); currentHostname = System.Net.Dns.GetHostName(); Commands.Initialize(); BotClient = new TelegramBotClient(APIKEY); var me = BotClient.GetMeAsync().Result; Username = me.Username; MyId = me.Id; Data.Utils.Logging.AddLog(new Models.SystemLog() { LoggerName = CacheData.LoggerName, Date = DateTime.Now, Function = "Unifiedban Terminal Startup", Level = Models.SystemLog.Levels.Warn, Message = $"Hello, World! I am user {me.Id} and my name is {me.FirstName}.", UserId = -1 }); MessageQueueManager.AddChatIfNotPresent(CacheData.ControlChatId); BotClient.OnMessage += BotClient_OnMessage; BotClient.OnCallbackQuery += BotClient_OnCallbackQuery; Console.Title = $"Unifiedban - Username: {me.Username} - Instance ID: {instanceId}"; Data.Utils.Logging.AddLog(new Models.SystemLog() { LoggerName = CacheData.LoggerName, Date = DateTime.Now, Function = "Unifiedban Terminal Startup", Level = Models.SystemLog.Levels.Info, Message = "Bot Client initialized", UserId = -2 }); }