tucnak / telebot Goto Github PK
View Code? Open in Web Editor NEWTelebot is a Telegram bot framework in Go.
License: MIT License
Telebot is a Telegram bot framework in Go.
License: MIT License
Hello, the channel post is helpful to my bot. hope you see it
It returns:
GitHub repository at https://github.com/tucnak/telebot has no branch or tag "v0", "v0.N" or "v0.N.M"
I can get from gopkg.in/tucnak/telebot.v1
anyway.
2015/12/04 07:39:03 failed to get updates: json: cannot unmarshal number into Go value of type string
many
many times
Bot API allows taking a file from telegram servers using getFile
method, see documentation. Would be great if this functionality will be implemented in telebot!
The docs say that to send a message in response to receiving a message, you should write
bot.SendMessage(message.Chat, ...)
but with recent API changes, SendMessage
takes a User
, not a Chat
. At the least, the docs are wrong.
But there seems to be a shortcoming here. The Message
type has a Sender
field of type User
, but the docs say it may be empty for group chats. My bot receives messages from a group. How do I send messages back to the group?
Do you have any plan about implementing these APIs? I'm willing to help but need your suggestion :)
I read the docs of new APIs, found that new File
structure is identical to File struct
in telebot. But that structure is only used for download file from server, so I think something like func (b Bot) SaveFile(f File, localFile string) error
should be enough. Do you think this implementation is fine?
Hi.
I see that you're cheating with documentation to silently pass linters.
Please, fix that doc parts.
For example look into that line.
Thanks.
Or I got
โ Desktop go build helloworld.go
# command-line-arguments
./helloworld.go:10: undefined: log in log.Fatalln
After I import "log" , it builds successfully.
Sorry, I open an issue in wrong repository :(
New update:
https://core.telegram.org/bots/api#inline-mode
Hi everybody,
How can i use inline keyboards with this library ?
Is it enough that i fill InlineKeyboard in ReplyMarkup ?
Is it okay to add support to update message from webhook?
I did some research by adding a new method to type Bot
func (b *Bot) WebHook(url string, subscription chan Message) http.HandlerFunc
and seems working fine.
If you think it's acceptable to add such method, I can send a PR for you. Thanks
I set the goal to release v2
by the end of September (see updated 2.0 milestone). As it's going to be a pretty major release, I suggest re-thinking some of the API. Our biggest competitor, telegram-bot-api, 625 stars, is still superior to Telebot in terms of API, so I believe in order to stand out we must provide additional and moreover, sensible value. Telebot has always positioned itself as the framework, while our competitors were and will remain an API wrapper.
Here are some of the issues I'd like to address (in the order of significance).
Message
is the fattest type in Telebot, taking as much as 1544 bytes on my system (~1.5KB). Mainly because it stores lots of optional fields by-value. This is clearly borderline stupid and uncomfortable (you can't test optionals against nil) and I can't recall why I'd ever thought it was a good idea.
I trivially managed (d8b3194) to reduce memory usage of Message
down to 504 bytes (~0.5KB), making a 67.4% decrease in memory usage, which is pretty fucking good, considering Message is the most-used object. No more hassle around optionals also.
We currently use no reflection at all, which is probably a good thing. That said, I think introducing some light weight interface{}
-kind of reflection for "optional" parameters may be a good thing.
SendMessage()
/ Send()
// Definition
func (b *Bot) SendMessage(r Recipient, message string, options ...interface{}) error {}
// Use
b.SendMessage(user, "message") // <-- much better, isn't it?
b.SendMessage(user, "message", &SendOptions{})
In fact, we could go further and generalize it all the way down to Send()
:
// Definition
func (b *Bot) Send(r Recipient, things ...interface{}) error {}
// Use
b.Send(user, "message")
b.Send(user, "message", &SendOptions{})
b.Send(user, photo)
// Etc..
I wonder whether it'll damage Telebot's performance much, we can't really tell without proper benchmarking. That said, considering there's not much high load in Telegram world, we still must end up the fastest bloke on the block by a huge margin (comparing w/ e.g. Python implementations).
Pros:
Cons:
inferace{}
casting)Sendable
In fact, we could avoid losing some of the safety and a fair chunk of casting and still introduce a better API by introducing a Sendable
interface for all the sendable objects like Photo
, Audio
, Sticker
, etc:
type Sendable interface {
Send(*Bot) error
}
Each and every corresponding sendable type would implement the necessary actions (which quite differ from type to type). This could also be used as a part of a prettier Send(Recipient, ..interface{})
too.
I thought about it for some time now and I believe we could benefit from some sort of builder API for sending messages, like this:
// Use
bot.V()
.To(recipient)
.Text("This is a text message")
// .Photo(&photo) or any other sendable
.Markdown()
.Keyboard(keyboard)
.Error(handlerFunc)
.Send()
It looks so good!
I also thought about implementing things like a state machine (telebot users would need to specify a list of states their bot users can be in and also, specify relations between these states) and a global error handler. Unfortunately, I couldn't come up with a reasonable API for "plots" (a state machine) yet though. I usually panic on bot errors and handle them up the stack anyway, so classic if err != nil
error handling is rather redundant. I'd love to do things like:
bot.ErrorHandler = func(err error) {
panic(err)
}
bot.Handle("/start", func(c Context) {
bot.Send(c.Message.Sender, "Hello") // calls ErrorHandler() -> panic()
})
UPD: I also feel like we are ovelooking inline queries and callbacks from the API design perspective... Bot start/listen/serve is confusing also!
There are literally 11 absolutely identical MarshalJSON
methods for InlineQueryResult
structs. I propose to come up with some backwards compatible refactoring strategy.
I incline to make IQR just a simple interface{}
and Marshal corresponding structs in-place.
Hi. I have some questions.
Kicking - https://core.telegram.org/bots/api#kickchatmember
Unbanning - https://core.telegram.org/bots/api#unbanchatmember
NB: Make sure it feels great
Provide, if possible, an example on how to use callbacks
The inline example provided does not work although it does not crash. It just is silentt!
Also, I cannot get bot.Start to work, as if it were in an infinite loop
Hi,
I tried to implement a simple inline bot, but my generated ArticleResult create an error. This is my code for the ArticleResult an the Result:
result := telebot.ArticleResult{"bla", "blubb", "blablubb", telebot.ModeMarkdown, true, true, "", true, ""}
results := []telebot.Result{result}
if err := bot.Respond(query, results); err != nil {
fmt.Println("ouch:", err)
}
I get the error:
telebot: Bad request: Field "disable_web_page_preview" must be of type Boolean
I tried a bit in your code and found the fault in the MarshalJSON()
method of inline_article.go
.
There you create the byte stream for every key value pair with
const tpl = `"%s":"%s",`
b.WriteString(fmt.Sprintf(tpl, key, value))
but that inserts ""
around the bools. Telegram don't like that. ;)
I test the method with a hardcoded
if (key == "disable_web_page_preview") {
b.WriteString(`"disable_web_page_preview":true,`)
} else {
b.WriteString(fmt.Sprintf(tpl, key, value))
}
and this works! The program now says:
telebot: Bad request: Field "hide_url" must be of type Boolean
I think it would a better idea to add the ""
to the strings directly and then only use const tpl =
"%s":%s,``.
How I can I send a photo ?
Is any way to use telegram.me/your_bot?start=XXXX
with AnswerCallbackQuery
?
Can you show me a sample code ?
Building on go 1.3.3 yields these syntax errors
./bot.go:41: syntax error: unexpected range, expecting {
./bot.go:56: non-declaration statement outside function body
./bot.go:57: syntax error: unexpected }
What is the target go version and could we document it?
I've read over most of the code for this library. How do I tell my bot to join a channel?
Can't seem to figure this out. Thanks. Great library btw!
With the master branch having recently received (potentially?) backwards-incompatible changes, it might be a good idea to adopt a good tagging strategy and link to gopkg.in (like http://gopkg.in/tucnak/telebot.v1) in the README.
I personally use govendor so it doesn't affect me as much, but not everyone does so it may be beneficial, especially to people more new to go.
https://telegram.org/blog/games
God bless the Queen!
Hi!
First, thanks for this library it really helps me to create a pair of bot telegrams.
Second, are you willing to implement or to accept pull request for support inline-mode? As you should noticed Telegram recently added this interesting feature for bots that I think it will fit into telebot.
https://core.telegram.org/bots/api#replykeyboardmarkup
We still miss custom reply keyboards (which, so far, do work on mobiles only). Since I lost my cell phone, I am currently not being able to hack and, therefore, test these. If anyone needs this functionality, you are totally welcome to pull!
Can't receive User info from MessageEntity instance via such code:
for _, v := range message.Entities { if v.Type == telebot.EntityMention || v.Type == telebot.EntityTMention { fmt.Println("[Entity]", v) } }
Possible output:
[Entity] {mention 0 8 {0 }}
[MSG]: From ... in chat #b2: @Riketta
[Entity] {mention 4 8 {0 }}
[MSG]: From ... in chat #b2: qwe @Riketta aasas
Seems like entity.User contains nothing useful. Sorry if I'm doing smth wrong.
While executing the program, I'm getting
failed to get updates: telebot: Conflict: terminated by other long poll or web hook
The code which I used is same which is being used in the readme document.
Something like as mentioned below:
telebottoken := os.Getenv("TELEBOT_TOKEN")
bot, err := telebot.NewBot(telebottoken)
if err != nil {
fmt.Print(err)
return
}
bot.Messages = make(chan telebot.Message, 100)
pluginframework.Bot = bot
go HandleMessages(bot)
bot.Start(1 * time.Second)
I see,that bot shoud listen telegramm per time,but as i understand it uses cpu (simple while loop).
Does Telebot support Webhooks?
MessageEntity - https://core.telegram.org/bots/api#messageentity
Venue - https://core.telegram.org/bots/api#venue
NB: Don't forget to update Message accordingly.
When sending a message, I put in the variable answer in the form of json. Then I'm decoding it and I get the error "<telebot.types.Message instance at 0x29cc0e0> is not JSON serializable". This trouble is in the key of "Entity".
Wouldn't it be nice to have some way of running bots in debug mode with different levels of verbosity?
I want this.
Hi everybody
I have a question !!!
How can I get number of seen in channels ?
Does telegram have any way to read number of seen in channels ?
I use github.com/tucnak/telebot for my telegram bot. special tnx ๐
cannot use &mp (type *telebot.File) as type *telebot.Audio in argument to bot.SendAudio
The Telegram Bot API guide allows for:
But the current API available only allows for buttons to be strings
without being able to specify that the button can directly send a location.
@tucnak: can you extend the library to allow for this to happen? Or if you can guide me towards a possible solution, I can create a PR.
type Video struct {
Audio // File ???
Width int `json:"width"`
Height int `json:"height"`
.....
Hey @tucnak, thanks for creating this wonderful tool.
I'm using telebot
for a project and I had questions about testing my code. Are there good ways to mock SendMessage
and equivalent methods?
I try to execute example with go1.7 ubuntu 16.04:
`package main
import (
"log"
"os"
"time"
"github.com/tucnak/telebot"
)
func main() {
bot, err := telebot.NewBot(os.Getenv("BOT_TOKEN"))
if err != nil {
log.Fatalln(err)
}
messages := make(chan telebot.Message, 100)
bot.Listen(messages, 1*time.Second)
for message := range messages {
if message.Text == "/hi" {
bot.SendMessage(message.Chat,
"Hello, "+message.Sender.FirstName+"!", nil)
}
}
}
`
But,when i run i get error:
./mybot.go:8: import /home/user/golang/pkg/linux_amd64/github.com/tucnak/telebot.a: object is [linux amd64 go1.7.4 X:framepointer] expected [linux amd64 go1.3.3 X:precisestack] exit status 2
I use VS Code 1.8.1.
Can you help me?
Thank you!
Hi ,
Is there any way to remove a message from channel ?
Administrators can remove messages , but how about bots ?
My bot is an administrator
Hi Tucnak, I use your example to run my bot. when the traffic is risen up, I occasionally encounter no more messages are processed, even I restart the bot.
messages := make(chan telebot.Message)
bot.Listen(messages, 1*time.Second)
for message := range messages {
if message.Text == "/hi" {
bot.SendMessage(message.Chat,
"Hello, "+message.Sender.FirstName+"!", nil)
}
}
If I use curl command in terminal curl -X POST [api_url]/getUpdates , then I got 100 messages queuing. Is there any reason why messages channel is not able to pick up these messages.
This code raise a panic due to reinitiate var bot:
import (
"log"
"time"
"github.com/tucnak/telebot"
)
var bot *telebot.Bot
func main() {
bot, err := telebot.NewBot("SECRET TOKEN")
if err != nil {
log.Fatalln(err)
}
bot.Messages = make(chan telebot.Message, 1000)
bot.Queries = make(chan telebot.Query, 1000)
go messages()
go queries()
bot.Start(1 * time.Second)
}
func messages() {
for message := range bot.Messages {
// ...
}
}
func queries() {
for query := range bot.Queries {
log.Println("--- new query ---")
log.Println("from:", query.From.Username)
log.Println("text:", query.Text)
// Create an article (a link) object to show in our results.
article := &telebot.InlineQueryResultArticle{
Title: "Telegram bot framework written in Go",
URL: "https://github.com/tucnak/telebot",
InputMessageContent: &telebot.InputTextMessageContent{
Text: "Telebot is a convenient wrapper to Telegram Bots API, written in Golang.",
DisablePreview: false,
},
}
// Build the list of results. In this instance, just our 1 article from above.
results := []telebot.InlineQueryResult{article}
// Build a response object to answer the query.
response := telebot.QueryResponse{
Results: results,
IsPersonal: true,
}
// And finally send the response.
if err := bot.AnswerInlineQuery(&query, &response); err != nil {
log.Println("Failed to respond to query:", err)
}
}
}
The problem is you're setting a global var on bot which is fine but then in main you're reinitiate this var again
This will raise a panic in your go functions
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xb code=0x1 addr=0x0 pc=0x7990b]goroutine18 [running]:
panic(0x34eec0, 0xc82000a110)
/usr/local/Cellar/go/1.6.2/libexec/src/runtime/panic.go:481 +0x3e6
github.com/tucnak/telebot.(*Bot).SendMessage(0x0, 0x1502168, 0xc82005c7e0, 0xc8203be250, 0xc, 0x0, 0x0, 0x0)
/Users/nick/go/src/github.com/tucnak/telebot/bot.go:103 +0x1bb
main.messages(0xc8201fe0c0)
/Users/nick/go/src/github.com/njuettner/telebot/main.go:34 +0x396
created by main.main
/Users/nick/go/src/github.com/njuettner/telebot/main.go:21 +0x18d
exit status
what you could do is setting an global err or doing this exclusive in your main function
and then remove the colon, like:
bot, err = telebot.NewBot("SECRET TOKEN")
I would find it useful if the handlers introduced with #89 had an option to set a description and a category.
This would mean that you could automatically generate a 'help' handler.
The main problem that I see is that adding more arguments to the Handle func would be a breaking change (but on the other hand it's not that bad as the handler was only introduced 5 days ago).
https://core.telegram.org/bots/api#choseninlineresult
Handle event when user has sent a message to chat partner by inline query.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.