Telegram bots cover
Telegram bot

How to create Telegram Bot via C# (Reminder Bot)

Murad Aliyev
5 min readFeb 28, 2022

Introduction

Hello guys. Today we create a telegram bot with C#. First we need to create console application in visual studio. Our Bot will be simple reminder bot. For example save our data and remind for late. We can use SQLite as database and quartz for cronjob operation. Actually quartz is a package which help to everyday or every minute do some task for us in order to checking. Let me explain our plan.

message of bot

In our bot will be like that. We will write for example “/reminder eat 15:45” and it sends to message at 15:45. We should save to data (user id, task, time) in the database and check time every 5 minute.

Dependency

Then we open the package manager and install to Telegram.Bot, Microsoft.EntityFrameworkCore , Microsoft.EntityFrameworkCore.Sqlite, Microsoft.EntityFrameworkCore.Tools, Quartz packages. We need all of them.

Creating Telegram Bot

First we write to Bot father in the own telegram profile. We use this keyword and create our bot and set the name.

rule and command of telegram bots

Then we take our token. It is more important for using API. We should write in the program.cs like that:

using System;using Telegram.Bot;namespace Bot{public class Program{static private string Token { get; } = “YourToken”;static TelegramBotClient Bot = new TelegramBotClient(Token);[Obsolete]static async Task Main(string[] args){Bot.StartReceiving();Bot.OnMessage += Bot_OnMessage;Console.ReadLine();}[Obsolete]public static void Bot_OnMessage(object sender, Telegram.Bot.Args.MessageEventArgs e){Bot.SendTextMessageAsync(e.Message.Chat.Id,"Hello users");}
}
}

We can send to message our users. In this example we send to “Hello users” message. But we need that message have to start with /reminder. So we can use switch case block.

string text = e.Message.Text;string keyword = text?.Split(' ')[0];switch (keyword){case "/reminder"://some operation
break;
default:
Bot.SendTextMessageAsync(e.Message.Chat.Id, "don't recognize command");break;

So structure is done. We just need to create classes which one them do operation and getting argument for save database and other one will be cronjob for scheduler. First determine our database model. Our model consist of userId, task, time and complite status.

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Bot.Model{public class Reminder{public int Id { get; set; }public long UserId { get; set; }public string TaskName{ get; set; }public datatime TaskTime{ get; set; }public bool CompliteStatus { get; set; }}}

And we should write dbContext for create connection sqlite with console application.

using Bot.Model;using Microsoft.EntityFrameworkCore;using System;using System.Collections.Generic;using System.Data.SQLite;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Bot.Data{public class SqliteDbContext : DbContext{public DbSet<Reminder> Reminders { get; set; }protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder){optionsBuilder.UseSqlite("Data Source=ReminderData.db");}}}

Data Source is our database name. We open to package management console and follow this commands add migration firstmig and update-database . Then you look through that new folder as migrations are created.

Also we can show database Sqlite extensions like that:

sqlite extension

It means that our database connection is done. And one more thing for adding data into our table. We must add this in our project file.

project config

So in this case we should create class which its name is botOperation.cs and we add some methods.

public static async Task<string> AddReminder(long chatId,string text){string[] words = text.Split(' ');if(words.Length != 3){return "Please write correct";}string slug = words[1];datatime time;try{time = Convert.Convert.ToDateTime(words[2]);}catch (Exception){return "Please write correct date time";}using (SqliteDbContext database = new SqliteDbContext()){await database.AddAsync(new Reminder() { UserId = chatId, TaskName= slug, TaskTime= time, CompliteStatus = false });await database.SaveChangesAsync();return "Your task setted.";}}
public static async Task<bool> Reminder(datetime taskTime)
{
int result = DateTime.Compare(taskTime, DateTime.Now);
if( result>0 || result == 0){return true;}return false;
}

We involve this method when switch case is '/start' case. In finally we just need cron job operation which every minute check to the time. For this we use quartz library. We create new folder as /SchedulerServices and we add 2 classes as job.cs and schedule.cs . Structure is easy. schedule.cs is just for configuration and add the job. job.cs is just method which it run every minute.

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using Quartz;using Quartz.Impl;using Telegram.Bot;namespace Bot.ScheduleServices{public class Schedule{public static async Task SchedulJob(TelegramBotClient bot){StdSchedulerFactory factory = new StdSchedulerFactory();IScheduler scheduler = await factory.GetScheduler();await scheduler.Start();scheduler.Context.Put("bot",bot);IJobDetail job = JobBuilder.Create<JobApi>().WithIdentity("jobName", "jobGroup").Build();ITrigger trigger = TriggerBuilder.Create().WithIdentity("triggerName", " triggerGorup").StartNow().WithSimpleSchedule(x => x.WithIntervalInMinutes(10).RepeatForever()).Build();await scheduler.ScheduleJob(job, trigger);}}}

In code we set to the time. I write to 10 minute it means each 10 minutes method will be run. Let’s create job.cs file.

using Bot.Commands;using Bot.Data;using Bot.Model;using Microsoft.EntityFrameworkCore;using Quartz;using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Telegram.Bot;using Telegram.Bot.Args;using Telegram.Bot.Types;namespace Bot.ScheduleServices{class JobApi:IJob{[Obsolete]public  async Task Execute(IJobExecutionContext context){Console.WriteLine("Started...");var schedulerContext = context.Scheduler.Context;var bot = (TelegramBotClient)schedulerContext.Get("bot");using (SqliteDbContext db = new SqliteDbContext()){List<Reminder> reminder = await db.Reminders.ToListAsync();foreach (Reminder reminderItem in reminder){if (reminderItem.CompliteStatus == false){bool result = Commands.BotCommand.Reminder(reminderItem.TaskName, reminderItem.TaskTime);if (result == true){await Console.Out.WriteLineAsync("Found");reminderItem.CompliteStatus = true;await db.SaveChangesAsync();Message message = await bot.SendTextMessageAsync(reminderItem.UserId, "Congrultalation");}else{await Console.Out.WriteLineAsync("Checking...");}}if(reminderItem.CompliteStatus == true){db.Remove(reminderItem);await db.SaveChangesAsync();}}}}}}

Everything is done. We just add these methods to our main class program.cs

[Obsolete]static async Task Main(string[] args){Bot.StartReceiving();await Schedule.SchedulJob(Bot);Bot.OnMessage += Bot_OnMessage;Console.ReadLine();}

And also add method for switch case statement.

switch (keyword){case "/reminder":var msg = BotOperation.AddReminder(e.Message.Chat.Id, text);Bot.SendTextMessageAsync(e.Message.Chat.Id, msg.Result.ToString());break;
default:
Bot.SendTextMessageAsync(e.Message.Chat.Id, "don't recognize command");break;

And That’s all our bot is ready.

Conclusion

I hope you enjoy and learn about dotnet and how to create telegram bot with reminder functions. I deploy github repo. But it doesn’t same with our project. It is more advanced than this. If you want please check it:https://github.com/murafalizade/TgBot

See you soon !

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Murad Aliyev
Murad Aliyev

Written by Murad Aliyev

Hi, I’m a Software Developer passionate about innovation and knowledge-sharing. I write blogs to empower developers and contribute to the tech community growth!

No responses yet

Write a response