Coder Social home page Coder Social logo

telegrambots / telegram.bot Goto Github PK

View Code? Open in Web Editor NEW
3.0K 143.0 675.0 31.95 MB

.NET Client for Telegram Bot API

Home Page: https://telegrambots.github.io/book

License: MIT License

C# 99.92% Dockerfile 0.08%
telegram telegram-bot telegram-bot-api chatbot bot

telegram.bot's Introduction

.NET Client for Telegram Bot API

package Bot API Version documentations telegram chat

build build downloads contributors license

Gitpod Ready-to-Code

Telegram.Bot is the most popular .NET Client for 🤖 Telegram Bot API.

The Bot API is an HTTP-based interface created for developers keen on building bots for Telegram.

Check 👉 Bots: An introduction for developers 👈 to understand what a Telegram bot is and what it can do.

We, the Telegram Bots team, mainly focus on developing multiple NuGet packages for creating chatbots.

➡️ If Bot API is too limited for your use cases you can try Telegram Client API implementation written 100% in C# https://github.com/wiz0u/WTelegramClient

Package Documentation News Channel Team Group Chat
package documentations News Channel Team Group Chat
This package on NuGet Telegram bots book Subscribe to 📣 @tgbots_dotnet channel to get our latest news The team contributing to this work Join our chat 💬 to talk about bots and ask questions

🔨 Getting Started

Please check ➡️ the Quickstart guide.

🚧 Supported Platforms

Project targets .NET Standard 2.0 and .NET 6 at minimum.

📦 Extension Packages

This project is referred to as the core package and is always required for developing Telegram bots. There are extension packages that you can include in your bot projects for additional functionality:

✅ Correctness & Testing

This project is fully tested using Unit tests and Systems Integration tests before each release. In fact, our test cases are self-documenting and serve as examples for Bot API methods. Once you learn the basics of Telegram chatbots, you will be able to easily understand the code in examples and use it in your own bot projects.

🗂 References

telegram.bot's People

Contributors

a-a-k avatar adebisi-fa avatar antkon avatar awskt avatar banane9 avatar bloodshadow174 avatar buldo avatar cristiant avatar dependabot[bot] avatar derigel23 avatar dragonsangel avatar fedorus avatar immmdreza avatar jansivans avatar karb0f0s avatar kipters avatar kolesnikov-sergey avatar mihazupan avatar mrachini avatar mrroundrobin avatar mrzoidberg avatar olfi01 avatar peterbozso avatar poulad avatar rgbweb avatar schjan avatar sohrablou avatar thoemmi avatar truil avatar tuscen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

telegram.bot's Issues

[Feature Request] A multilevel keyboard in a single command

Hi, We really appreciated your bot API, and we want to use this API to create own bot for business.
Basically our requirement is that we want select product by asking multiple question with selective option

Example: our user want buy smartphone we want to implement in following steps
Step 1) Brand : Apple, Samsung, BlackBerry [Next]
Step 2) [Back] Memory : 8gb, 16gb, 32gb, 64gb [Next]
Step 3) [Back] Camera : 8mp , 16mp [Next]
Step 4) [Back] Budget : 10000-14999, 15000-24900 , above 25000 [Finish]

As we mentioned our scenario as above, first we will show Brand, then Memory, then Camera and finally Budget, in which user can select multiple values too.
We want to provide all this feature in a single keyboard selection event, which can be operated by a user in ease way.
In current scenario, a user waits until next filter category is shown, and all this category is shown one by one until the user clicks the finish. Unfortunately this conversation will be too long, and tricky if user wants to change any filtration category (with [Next] or [Back] button as we mentioned in example). We can only send list of products after finish event occurs. But instead of that, we want to have a keyboard in which a user can select values and that selection appears in typing area, which can be changed and submitted at only final state in one single message.

requests in the queue?

hi
for example, if 50 requests send from user A, after that run the application, after that send 1 request from user B,when the answer to user B? Probably act program such as queue, if your app acts such as queue and assume each request needs one second time to answer, so answer to user B after 50 seconds?
is it right?

how to use Force Reply ?

hi

i want to force user to enter reply message
i wrote following code , but telegram didn't show reply message keyboard , just show simple message
string data = new StreamReader(Request.InputStream).ReadToEnd().ToString().Trim();
Telegram.Bot.Types.Update update = Telegram.Bot.Types.Update.FromString(data);
Telegram.Bot.Api api = new Telegram.Bot.Api("myapicode");
api.SendTextMessage(update.Message.From.Id, "test", false, 0, new ForceReply());

is my code right ?

get groups title

Hi.
How can i get groups title?

i can't find code in this API.

Error in sample project

Error in sample project

System.AggregateException
HResult=-2146233088
Source=mscorlib
StackTrace:
в System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
в System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
в System.Threading.Tasks.Task.Wait()
в XXXBotTest.Program.Main(String[] args) в c:\users\xxx\documents\visual studio 2015\Projects\XXXBotTest\XXXBotTest\Program.cs:строка 14
в System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
в System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
в Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
в System.Threading.ThreadHelper.ThreadStart_Context(Object state)
в System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
в System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
в System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
в System.Threading.ThreadHelper.ThreadStart()
InnerException:
HResult=-2146233088
Message=Error: Bad Request: Not in chat
Source=Telegram.Bot
StackTrace:
в Telegram.Bot.Api.d__691.MoveNext() --- Конец трассировка стека из предыдущего расположения, где возникло исключение --- в System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) в System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) в System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
в Telegram.Bot.Api.d__12.MoveNext()
--- Конец трассировка стека из предыдущего расположения, где возникло исключение ---
в System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
в System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
в System.Runtime.CompilerServices.TaskAwaiter1.GetResult() в Telegram.Bot.Api.<SendTextMessage>d__19.MoveNext() --- Конец трассировка стека из предыдущего расположения, где возникло исключение --- в System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) в System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) в System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
в XXXBotTest.Program.d__1.MoveNext() в c:\users\xxx\documents\visual studio 2015\Projects\XXXBotTest\XXXBotTest\Program.cs:строка 34
InnerException:

more sample

hi , sorry for sending post here , would you please publish more sample of code ?

Problem in Version 4!

I updated your nice lib to my applicaion... (Version 4)

But unfortunately sending Phone, Audio,... does not response!

It means that the file will be uploaded but after sendAudio, SendPhoto... system freazes!

Regards
Dariush Tasdighi

Hello - How to Start

    Api TelApi = new Api("101860982:AAF4dszej2cJ9rzElp-lmVPuua-hC51t8n4");

    private async void BtnStart_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            Telegram.Bot.Types.User UserMe = await TelApi.GetMe();
            MessageBox.Show(UserMe.FirstName);
        }
        catch (Exception EX)
        {
            MessageBox.Show(EX.Message);
        }
    }

Some one Help me to solve the problem !>?
when I run this code Error 502 (Bad GateWay) pops up!
Help please !?

Message.cs

when you dont make new object of properties inside Message.cs
when we recive message that doesent have replay from, we get error, like
public User From; that should change to => public User From = new User();
getters with type object should refer to another private object in class
or should get new theirselves.

i got error that object not set to instant object many times, event when you check for null you recive error
making new object of objects inside message.cs fixed problem !

Error In Sending Icon's as a Document !

HI,
First I want to Thanks you for your great library 👍

now on to the issue ,
it seems that Telegram's document , when sending an icon , in the thumb field, is empty !
thus giving error , as u made it in your code that if there is a thumb , then width + height + field_id are all Required !
they are always there if u send other kind of documents so it's fine , but for icon , this error happened ,
I temporary fixed it by setting these three to default which is not required , but i don't know if u want to make a better change for it :D

Here a Json for Icon :

{"ok":true,"result":[{"update_id":918502747,
"message":{"message_id":188,"from":
{"id":120865239,"first_name":"Pedram","last_name":"Saeedi"},"chat":
{"id":120865239,"first_name":"Pedram","last_name":"Saeedi"},"date":1436357039,"document":
{"file_name":"favicon.ico","mime_type":"image\/vnd.microsoft.icon","thumb":
{},"file_id":"BQADBAADCAAD10E0BwVrR0oxKKibAg","file_size":2462}}}

set webhook example?

Hi,

I'm very new in this telegram things.
can you help me and make an example for using webhook and certificate parameter?

I just don no how to use webhook in my C# program,
before this certificate parameter I was working with getupdate.

Thanks...

Proxy

It does not wpork with proxy

Message.cs

Line 110 wrong writing,
new_chat_patricipant should be new_chat_participant.

Telegram Added support for self-signed certificates

Hello.
Thank you so mush for creating this free package. telegram recently Added support for self-signed certificates for web hook. please update your setwebhook method.
and if its not so mush trouble i really appreciated if you could create a little sample code for uploading files. i don't know how telegram send a file_id.
thank you.

CoreClr support

Add support for CoreClr, please.
Here is example project.json:

{
  "version": "1.0.0-*",
  "description": "Telegram.Bot Class Library",
  "authors": [ "" ],
  "tags": [ "" ],
  "projectUrl": "",
  "licenseUrl": "",
  "dependencies": {
    "System.Net.Http": "4.0.1-beta-23409",
    "Newtonsoft.Json": "7.0.1"
  },
  "frameworks": {
    "dnx451": { },
    "dnxcore50": {
      "dependencies": {
        "Microsoft.CSharp": "4.0.1-beta-23409",
        "System.Collections": "4.0.11-beta-23409",
        "System.Linq": "4.0.1-beta-23409",
        "System.Runtime": "4.0.21-beta-23409",
        "System.Threading": "4.0.11-beta-23409"
      }
    }
  }
}

Unhandled Exception in GetUpdates

Encountered exception in GetUpdates function.

Unhandled Exception: System.AggregateException: One or more errors occurred. ---

System.Net.Http.HttpRequestException: An error occurred while sending the requ
est. ---> System.Net.WebException: The underlying connection was closed: The con
nection was closed unexpectedly.
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
--- End of inner exception stack trace ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNot
ification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAw aiter.GetResult() at Telegram.Bot.Api.<SendRequest>d__28.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNot ification(Task task) at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAw
aiter.GetResult()
at Telegram.Bot.Api.d__261.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNot ification(Task task) at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAw
aiter.GetResult()
at Telegram.Bot.Api.d__5.MoveNext()
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceled
Exceptions)
at System.Threading.Tasks.Task1.GetResultCore(Boolean waitCompletionNotifica tion) at System.Threading.Tasks.Task1.get_Result()
at SmartTeleBot.Program.Main()

Code:

while (true)
{
    try
    {
        updates = bot.GetUpdates(offset);
    }
    catch { }

    try
    {
        // encountered error in 'updates.Result'
        foreach (Telegram.Bot.Types.Update update in updates.Result)
        {
            // Do some work
        }
    }
    catch (Exception ex)
    {
        // Error handling.
    }
}

api.SendTextMessage(...) not working

Tried calling it with working IDs and always the response status code is 400 (Bad Request). Also tried my own ID, even than it's still not working.

Exception details:

System.Net.Http.HttpRequestException
Response status code does not indicate success: 400 (Bad Request).

MessageType == operator overload

Hi
The == overload is explicitly doing a ReferenceEquals rather than using the Equals method in the class.
This can't be the desired implementation, surely?
Paul

Telegram bot API doesnt send any updates

Hello.
i want to receive the updates with telegram web hook. i create a WCF web service with https binding. here is my web service address:
https://telegram.simclub.ir/Telegram/ReceiveTelegramUpdates.svc

my web service only has a one method. here is my web service class:

[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = @"/Update")]
[Description("Use This Method To Update The Bot")]
void Update(string update);

i received the updates but telegram sends a null string to me!!. i have no idea what is going on. would you please help me?
Thanks.

Send Document

Hi,
How to send file from my computer with SendDocument function ?

exception in GetUpdates

Hi,

I am using the last NuGet package 2.0.0.248
After long period of calling GetUpdates in a loop (a few hours)
the following exception is sometimes thrown (from GetUpdates):

System.Net.Http.UnsupportedMediaTypeException: No MediaTypeFormatter is available to read an object of type 'ApiResponse1' from content with media type 'text/html'. at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)
at System.Net.Http.HttpContentExtensions.ReadAsAsync[T] (HttpContent content, Type type, IEnumerable1 formatters, IFormatterLogger formatterLogger)
at System.Net.Http.HttpContentExtensions.ReadAsAsync[T] (HttpContent content, IEnumerable1 formatters) at System.Net.Http.HttpContentExtensions.ReadAsAsync[T] (HttpContent content) at Telegram.Bot.Api.<SendWebRequest>d__241.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
at Telegram.Bot.Api.d__4.MoveNext()

In calling 'SendVideo' method, an error occurs

hi
Error:
A task was canceled.

Code:

var stream = new FileStream(fi.FullName, FileMode.Open);
var fileToSend = new FileToSend(fi.Name, stream);
await rBot.SendVideo(update.Message.Chat.Id, fileToSend,0, "", 0, Menus.UserMenu.UserMenuKeyboard);

File info:
.mp4, 4m

I think request times out and throws a WebException.
ty.

Get_Updates function

Hi.
please check this code...
when Get_Updates function is returned empty or when get a error in get url request, function return null.
this code is true??

        public async Task<Update[]> GetUpdates(int offset = 0, int limit = 200, int timeout = 0)
        {
            try
            {
                var parameters = new Dictionary<string, object>
                {
                    {"offset", offset},
                    {"limit", limit},
                    {"timeout", timeout}
                };
                return await SendWebRequest<Update[]>("getUpdates", parameters).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                int err = ex.HResult;
                Update[] up = new Update[0];
                return up;
            }
        }

please any help?

I want to load telegram.org in my WindowsFormsApplication with C# in webBrowser with this code:
webBrowser1.Navigate("https://web.telegram.org");
But result is empty.
How can I load this site?
thanks

How to set thumbnail when using sendvideo method

Hi
How can I set thumbnail when using sendvideo method ?
byte[] videoDate;
using (var wc = new WebClient())
videoDate = wc.DownloadData(videoUrl);

var response = await
_api.SendVideo(update.Message.Chat.Id,
new FileToSend(videoUrl, new MemoryStream(videoDate)), 15, myBotAdMsg, 0,
new ReplyKeyboardMarkup
{
Keyboard = _nextVideoCommands,
OneTimeKeyboard = true,
ResizeKeyboard = true
});

http://oi60.tinypic.com/33ml5pj.jpg

Also response.video.thumb is null !!?

Thanks .

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.