Git Product home page Git Product logo

telegrambotsexample's Introduction

Telegram Bot Java Library

Build Status Telegram

Samples for TelegramBots library

Translations

Bots are now supporting multilanguage. If you want to add your own, feel free to translate at transifex

Contributions

Feel free to fork this project, work on it and then make a pull request agains dev branch.

Most of the times I will accept them if they add something valuable to the code.

Please, DO NOT PUSH ANY TOKEN OR API KEY, I will never accept a pull request with that content.

Telegram Bot API

This library use Telegram bot API, you can find more information following the link.

Questions or Suggestions

Feel free to create issues here as you need

Usage with eclipse

Follow the steps created by Rico here

Tutorial

Short tutorial how to make a simple Echo Bot is available here

License

This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/.

telegrambotsexample's People

Contributors

clevero avatar dapoldi avatar ixplo avatar kytmanov avatar mit0x2 avatar rubenlagus 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

telegrambotsexample's Issues

Really necessary mySql using?

Can I disable database using, or use sqlite? If i simply change driver, it blow up on syntax problems in hardcoded queries.

Configuration in BotConfig

- next, go to org.telegram and edit `BotConfig.java`
Here we must fill in our login credentials for our bot.
public static final String TOKENMYPROJECT = "[YOUR_TOP_SECRET_TOKEN]";
public static final String USERNAMEMYPROJECT = "myProjectBot";

Hello!
In BotConfig.java where is TOKENMYPROJECT and USERNAMEMYPROJECT ???

Thanks

group chat

i don´t know if its a bug or i have missed something but i don´t get a callback when a group message is written without say it directly to the bot with @ Botname.

Execution bot

I saw her example of buttons respond very fast in the telegram, which secret in execution? Machine? configuration?

JDBC Connection is closed automatically

The problem is that after some time JDBC closes connection with MySQL database and there is no method in code to reload connection. Maybe I looked not too attentively. Can you help? Thanks in advance

Help, A tutorial?

I know this is not an issue, but I need help to create a bot, I don't even know how start.
I put the bot token and run Main.java and just errors

"Oct 26, 2015 2:15:56 PM org.apache.http.impl.execchain.RetryExec execute
INFO: I/O exception (java.io.FileNotFoundException) caught when processing request to {s}->https://api.telegram.org:443: path/to/my/certkey.pem (No such file or directory)
Oct 26, 2015 2:15:56 PM org.apache.http.impl.execchain.RetryExec execute
INFO: Retrying request to {s}->https://api.telegram.org:443
Oct 26, 2015 2:15:56 PM org.apache.http.impl.execchain.RetryExec execute
INFO: I/O exception (java.io.FileNotFoundException) caught when processing request to {s}->https://api.telegram.org:443: path/to/my/certkey.pem (No such file or directory)
Oct 26, 2015 2:15:56 PM org.apache.http.impl.execchain.RetryExec execute
INFO: Retrying request to {s}->https://api.telegram.org:443
Oct 26, 2015 2:15:56 PM org.apache.http.impl.execchain.RetryExec execute
INFO: I/O exception (java.io.FileNotFoundException) caught when processing request to {s}->https://api.telegram.org:443: path/to/my/certkey.pem (No such file or directory)
Oct 26, 2015 2:15:56 PM org.apache.http.impl.execchain.RetryExec execute
INFO: Retrying request to {s}->https://api.telegram.org:443
Exception in thread "main" java.lang.NullPointerException
at org.telegram.database.ConectionDB.checkVersion(ConectionDB.java:72)
at org.telegram.database.DatabaseManager.(DatabaseManager.java:38)
at org.telegram.database.DatabaseManager.getInstance(DatabaseManager.java:55)
at org.telegram.updatesreceivers.UpdatesThread.(UpdatesThread.java:47)
at org.telegram.updateshandlers.FilesHandlers.(FilesHandlers.java:48)
at org.telegram.Main.initBots(Main.java:37)
at org.telegram.Main.main(Main.java:24)
"
Don't even know what to do next, or why is the error, I would like to know if there is even a simple tutorial using this library.

BuildVars - explanation

Try to start a simple Echo Bot.

But I have some problems with settings in BuildVars.java

For what is EXTERNALWEBHOOKURL and INTERNALWEBHOOKURL?

Can those be set to my domain/ip of my server?

Numeric value (6011222546) out of range of int

Json数据 转对象失败,id 字段超出数值范围。

[hdwmp_bot Telegram Connection] ERROR org.telegram.telegrambots.updatesreceivers.DefaultBotSession - Unable to deserialize response
org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException: Unable to deserialize response
	at org.telegram.telegrambots.meta.api.methods.updates.GetUpdates.deserializeResponse(GetUpdates.java:96)
	at org.telegram.telegrambots.updatesreceivers.DefaultBotSession$ReaderThread.getUpdatesFromServer(DefaultBotSession.java:263)
	at org.telegram.telegrambots.updatesreceivers.DefaultBotSession$ReaderThread.run(DefaultBotSession.java:192)
Caused by: com.fasterxml.jackson.databind.JsonMappingException: Numeric value (6011222546) out of range of int (-2147483648 - 2147483647)
 at [Source: (String)"{"ok":true,"result":[{"update_id":980627982,
"message":{"message_id":3,"from":{"id":102427854,"is_bot":false,"first_name":"hdwmp123","username":"hdwmp123","language_code":"zh-hans"},"chat":{"id":-1001881772875,"title":"KingGroup","username":"kinggroup2","type":"supergroup"},"date":1675933864,"new_chat_participant":{"id":6011222546,"is_bot":true,"first_name":"KingChatGpt","username":"mujo_chatgpt_bot"},"new_chat_member":{"id":6011222546,"is_bot":true,"first_name":"KingChatGpt","username":"mujo_ch"[truncated 3290 chars]; line: 2, column: 504] (through reference chain: org.telegram.telegrambots.meta.api.objects.ApiResponse["result"]->java.util.ArrayList[0]->org.telegram.telegrambots.meta.api.objects.Update["message"]->org.telegram.telegrambots.meta.api.objects.Message["new_chat_members"]->java.util.ArrayList[0]->org.telegram.telegrambots.meta.api.objects.User["id"])
	at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:397)
	at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:356)
	at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.wrapAndThrow(BeanDeserializerBase.java:1726)
	at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:295)
	at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:156)
	at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:290)
	at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:249)
	at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:26)
	at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:129)
	at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:293)
	at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:156)
	at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:129)
	at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:293)
	at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:156)
	at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:290)
	at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:249)
	at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:26)
	at com.fasterxml.jackson.databind.deser.impl.FieldProperty.deserializeAndSet(FieldProperty.java:138)
	at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:293)
	at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:156)
	at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4526)
	at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3468)
	at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3451)
	at org.telegram.telegrambots.meta.api.methods.updates.GetUpdates.deserializeResponse(GetUpdates.java:88)
	... 2 more

org.telegram.telegrambots.meta.api.objects.User

属性

id

How to disable WebHook?

Hi all,
I'm using your echo sample but I have a problem.
I set maven parameters in my pom.xml and changed to "false" the boolean var "useWebHook" in BuildVars.java.
It compiles without errors but at runtime the following exception is raised
java.lang.NoClassDefFoundError: org/apache/http/conn/ssl/NoopHostnameVerifier
at org.telegram.telegrambots.TelegramBotsApi.setWebhook(TelegramBotsApi.java:98)
at org.telegram.telegrambots.TelegramBotsApi.setWebhook(TelegramBotsApi.java:152)
at org.telegram.telegrambots.TelegramBotsApi.registerBot(TelegramBotsApi.java:129)

Thanks

org.telegram.database.ConectionDB.checkVersion null pointer exception

Exception in thread "main" java.lang.NullPointerException
at org.telegram.database.ConectionDB.checkVersion(ConectionDB.java:72)
at org.telegram.database.DatabaseManager.(DatabaseManager.java:38)
at org.telegram.database.DatabaseManager.getInstance(DatabaseManager.java:55)
at org.telegram.updatesreceivers.UpdatesThread.(UpdatesThread.java:50)
at net.yazeed44.cdpnebot.CdpneIntroBot.(CdpneIntroBot.java:28)
at net.yazeed44.cdpnebot.Main.main(Main.java:9)

How to update bot in production mode?

Hey, I thought about updating my bot while he is still in production mode and could possibly do something at the moment.

I came out with this solution:

Creating a new class that is responsible for interactions with the server console

public class BotMaster extends Thread {

    private BotSession session;

    public void run(){

        Scanner scanner = new Scanner(System.in);
        String c;
        while((c = scanner.nextLine()) != null){
            if(c.equals("stop")){

                System.out.println("[INFO] Start shutting down this instance");
                this.session.close();
                System.out.println("[OK] Closed session. Up to now, we cannot receive any updates. Shutting down program when there are no more pending actions");
                while(EchoHandler.isInUse()){
                    try {
                        Thread.sleep(1000L);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }//end catch()
                }//end while()
                System.out.println("[OK] Shutting down full instance");
                scanner.close();
                currentThread().interrupt();
                break;
            }//end if()
        }//end while()

    }//end run()

    public void setSession(BotSession session){
        this.session = session;
    }//end setSession()

}//end class

Added also one method to my updatehandler

private static int pendingActions;

public static boolean isInUse(){
        return !(EchoHandler.pendingActions == 0);
}//end isInUse()

Every time onUpdateReceived() is called, pendingActions is counted up, and before end of the method call it's also counted down

My Main.java

public static void main(String[] args) throws IOException, InterruptedException {
        BotSession session= null;
        BotMaster master = new BotMaster();
        master.start();
        TelegramBotsApi telegramBotsApi = new TelegramBotsApi();
        try {
            session = telegramBotsApi.registerBot(new EchoHandler());
            master.setSession(session);

        } catch (TelegramApiException e) {
            BotLogger.error(LOGTAG, e);
            System.out.println(e.getApiResponse());

        }//end catch()
        while(master.isAlive()){

        }//end while()
        System.exit(-1);
    }//end main()

How I use it

  • type stop into the server console <- now this instance cannot receive any updates. But it can send something
  • next instance is started <- this instance is now responsible for new updates.
  • the old instance will shut down when all pending actions are processed

Has anybody a better way to update bots in production mode?

API response format seems different from what library expects

I'm using maven to add the library and I can successfully run the test echobot.

However, it doesn't echo the message back. The Update Object passed into the variable is:

Message{
messageId=7,
from=User{
id=201714380,
firstName='pelumi',
lastName='null',
userName='null'
},
date=1461823588,
chat=Chat{
id=201714380,
type='private',
title='null',
firstName='pelumi',
lastName='null',
userName='null'
},
forwardFrom=null,
forwardDate=null,
text='hey',
audio=null,
document=null,
photo=null,
sticker=null,
video=null,
contact=null,
location=null,
venue=null,
newChatMember=null,
leftChatMember=null,
newChatTitle='null',
newChatPhoto=null,
deleteChatPhoto=null,
groupchatCreated=null,
replyToMessage=null,
voice=null,
superGroupCreated=null,
channelChatCreated=null,
migrateToChatId=null,
migrateFromChatId=null
}

As seen the Message object is not null which makes it enter the if case as expected. Conversely, the message object doesn't contain a property 'text'. Text is a property of the parent 'Update' object meaning the method if (message.Hastext()) return false.

My question is this, am I using the wrong (or un-updated) library or the response format just changed recently and the client needs to be updated?

I added the library using maven as seen below (added the repo and the actual dep):

<repositories>
    <repository>
        <id>jitpack.io</id>
        <url>https://jitpack.io</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>com.github.rubenlagus</groupId>
        <artifactId>TelegramBots</artifactId>
        <version>V2.2</version>
    </dependency>
</dependencies>

Jar for Android?

is ot possible to compile this into JAR and use in android project?

Need help with start bot

Almost sure that the problem is on my side but I can not find the reason

I catch exception on bot starting
org.telegram.telegrambots.exceptions.TelegramApiRequestException: Error removing old webhook at org.telegram.telegrambots.bots.TelegramLongPollingBot.clearWebhook(TelegramLongPollingBot.java:32) at org.telegram.telegrambots.TelegramBotsApi.registerBot(TelegramBotsApi.java:120) at ru.npte.sloth.telehelper.telegram.SlothHelperBot.initTelegramApi(SlothHelperBot.kt:55) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:365) at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:308) at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:135) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:424) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1700) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:581) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:503) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:760) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:395) at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) at org.springframework.boot.SpringApplication.run(SpringApplication.java:1255) at org.springframework.boot.SpringApplication.run(SpringApplication.java:1243) at ru.npte.sloth.telehelper.TelehelperApplicationKt.main(TelehelperApplication.kt:16) Caused by: org.telegram.telegrambots.exceptions.TelegramApiException: Unable to execute deleteWebhook method at org.telegram.telegrambots.bots.DefaultAbsSender.sendApiMethod(DefaultAbsSender.java:691) at org.telegram.telegrambots.bots.AbsSender.execute(AbsSender.java:53) at org.telegram.telegrambots.bots.TelegramLongPollingBot.clearWebhook(TelegramLongPollingBot.java:27) ... 27 more Caused by: java.net.SocketException: Connection reset at java.net.SocketInputStream.read(SocketInputStream.java:210) at java.net.SocketInputStream.read(SocketInputStream.java:141) at sun.security.ssl.InputRecord.readFully(InputRecord.java:465) at sun.security.ssl.InputRecord.read(InputRecord.java:503) at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:983) at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1385) at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1413) at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1397) at org.apache.http.conn.ssl.SSLConnectionSocketFactory.createLayeredSocket(SSLConnectionSocketFactory.java:396) at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:355) at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:142) at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:373) at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:381) at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:237) at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:185) at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89) at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:111) at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:108) at org.telegram.telegrambots.bots.DefaultAbsSender.sendHttpPostRequest(DefaultAbsSender.java:737) at org.telegram.telegrambots.bots.DefaultAbsSender.sendMethodRequest(DefaultAbsSender.java:733) at org.telegram.telegrambots.bots.DefaultAbsSender.sendApiMethod(DefaultAbsSender.java:688) ... 29 more

I will be happy with any advice

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.