How to build a Telegram bot to suggest you pizza using java? - java

I created a Main java file and I added an instruction for the bot: say "I love Pizza" on a public channel I created.
public class Main {
public static void main(String[] args) {
//create a new Telegram bot object to start talking with Telegram
TelegramBot bot = TelegramBotAdapter.build(“HERE YOUR API KEY”);
bot.sendMessage(“#pizzaciaopizza”, “I love Pizza”);
}
}
This worked. Good start. Thankfully my bot loves pizza.
I wanted to enable my bot to answer a command like "/recommendPizza" and to answer something.So how can one do this?
Any help?

You seem to be using https://github.com/pengrad/java-telegram-bot-api, right?
I have previously used https://github.com/rubenlagus/TelegramBots. It provides a simple listener API to receive updates:
public class PizzaBot {
private static final Logger LOG = Logger.getLogger(PizzaBot.class.getName());
public static void main(String... args) throws Exception {
TelegramBotsApi telegramBotsApi = new TelegramBotsApi();
telegramBotsApi.registerBot(new TelegramLongPollingBot() {
#Override
public void onUpdateReceived(Update update) {
Message message = update.getMessage();
Long chatId = message.getChatId();
String input = message.getText();
if ("/recommendPizza".equals(input)) {
SendMessage request = new SendMessage();
request.setChatId(chatId.toString());
request.setText("Have a calzone!");
try {
sendMessage(request);
} catch (TelegramApiException e) {
LOG.log(Level.SEVERE, "Could not send message", e);
}
}
}
#Override
public String getBotUsername() {
return "YOUR_BOT_USERNAME";
}
#Override
public String getBotToken() {
return "YOUR_BOT_TOKEN";
}
});
}
}

Related

Discord JDA onGuildMemberJoin not working

I have this code:
public class Main extends ListenerAdapter {
public static void main(String[] args) {
try{
JDA jda = JDABuilder.createDefault("MyToken")
.addEventListeners(new Main()).build();
}catch(Exception e){
System.out.println(e.getMessage());
}
}
#Override
public void onGuildMemberJoin(GuildMemberJoinEvent event)
{
User user = event.getUser();
TextChannel textChannel = event.getGuild().getTextChannelById("myChannelId");
textChannel.sendMessage(String.format("%s %s", "Welcome, ", user.getName())).queue();
}
}
I think this should working? I just want the bot to say "Welcome" in a specific channel when a member join the server but nothing append when I run that and join my server.
Any solutions?

Why does the program close immediately after launch?

Please tell me why my program ends immediately after launch. It's a Java Telegram Bot running on my home PC. I created the project using Maven.
MainClass
public class MainClass extends TelegramWebhookBot {
BootConfig cfg = new BootConfig();
public static void main(String[] args) {
ApiContextInitializer.init();
TelegramBotsApi telegramBotsApi = new TelegramBotsApi();
try {
telegramBotsApi.registerBot(new MainClass());
} catch (TelegramApiException ex) {
ex.printStackTrace();
}
}
#Override
public BotApiMethod onWebhookUpdateReceived(Update update) {
if (update.hasMessage() && update.getMessage().hasText()) {
SendMessage sendMessage = new SendMessage();
sendMessage.setChatId(update.getMessage().getChatId().toString());
sendMessage.setText("Well, all information looks like noise until you break the code.");
return sendMessage;
}
return null;
}
#Override
public String getBotUsername() {
return cfg.WEBHOOK_USER;
}
#Override
public String getBotToken() {
return cfg.WEBHOOK_TOKEN;
}
#Override
public String getBotPath() {
return cfg.WEBHOOK_USER;
}
}
BootConfig class:
public class BootConfig {
public static final String WEBHOOK_TOKEN = "SECRET";
public static final String WEBHOOK_USER = "archopobbkbot";
Console output:
Process finished with exit code 0

unable to subscribe paho mqtt java

I'm new to mqtt. Getting started I tried publishing and subscribing topics to mosquitto broker. I was able to publish messages. But my subscriber is not listening to the topic, it will start and stop without waiting/polling for messages.
Here is the subscriber code,
public class MqttSubscriber implements MqttCallback {
private static final String TOPIC = "iot/endpoint";
public static void main(String[] args) {
new MqttSubscriber().listen();
}
public void listen() {
MqttClient client = null;
try {
client = MqttClientGenerator.generateSubscriberClient();
client.connect();
System.out.println("Fetching messages...");
client.subscribe(TOPIC);
client.setCallback(this);
client.disconnect();
} catch (MqttException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public void connectionLost(Throwable t) {
t.printStackTrace();
}
public void deliveryComplete(IMqttDeliveryToken arg0) {
}
public void messageArrived(String topic, MqttMessage message) throws Exception {
System.out.println("Message received from broker...");
System.out.println("Received Message: -- ");
System.out.println(message.getPayload().toString());
}
}
MqttClientGenerator :
public class MqttClientGenerator {
private static final String BROKER_URI = "tcp://localhost:1883";
private static final String CLIENT_ID = "pub";
private static final String SUBSCRIBER_ID = "sub";
private MqttClientGenerator () {}
public static MqttClient generatePublisherClient() throws MqttException{
//adding timestamp to make client name unique every time
return new MqttClient(BROKER_URI, CLIENT_ID+new Date().getTime());
}
public static MqttClient generateSubscriberClient() throws MqttException{
//adding timestamp to make client name unique every time
return new MqttClient(BROKER_URI, SUBSCRIBER_ID+new Date().getTime());
}
}
what am i missing here?
Try deleting the line where you disconnect the client.

Getting error while implement OutboundMessageListener in blackberry?

Getting error while using OutboundMessageListener and MessageListener by using this code:
public class MainClass extends UiApplication implements OutboundMessageListener,MessageListener
{
public static void main(String[] args)
{
MainClass mainClass = new MainClass();
mainClass.enterEventDispatcher();
}
public MainClass()
{
try
{
MessageConnection _mc = (MessageConnection)Connector.open("sms://");
_mc.setMessageListener(this);
}
catch (IOException e)
{
}
UiApplication.getUiApplication().pushScreen(new SmsCountScreen());
}
public void notifyIncomingMessage(MessageConnection conn)
{
UiApplication.getUiApplication().invokeAndWait(new Runnable()
{
public void run()
{
Dialog dialog = new Dialog(Dialog.D_OK, "Message Received!", 0, null, Dialog.FIELD_HCENTER);
Ui.getUiEngine().pushGlobalScreen(dialog, 1, UiEngine.GLOBAL_MODAL);
}
});
}
public void notifyOutgoingMessage(Message message)
{
UiApplication.getUiApplication().invokeAndWait(new Runnable()
{
public void run()
{
Dialog dialog = new Dialog(Dialog.D_OK, "Message Sent!", 0, null, Dialog.FIELD_HCENTER);
Ui.getUiEngine().pushGlobalScreen(dialog, 1, UiEngine.GLOBAL_MODAL);
}
});
}
}
using this code and getting error
IOException: operation not permitted on a client connection
Please help to solve this?
Looking at this example on the BlackBerry support forums, they use this code:
public class MyMessageListener implements OutboundMessageListener
{
public void notifyOutgoingMessage(javax.wireless.messaging.Message m)
{
try {
String msg = null;
msg = getMessage(m); // my call to convert Message to String
//... process msg
}
catch(Exception ex) {
// handle exception
}
}
public void notifyIncomingMessage(MessageConnection conn)
{
// handle received sms here
}
}
to register the listener
MyMessageListener ml = new MyMessageListener();
MessageConnection mc;
try {
mc = (MessageConnection)Connector.open("sms://:0");
mc.setMessageListener(el);
} catch (Exception e) {
// handle exception
}
Note that the port is specified in the Connection.open() URL. I'd also recommend testing this on a real device, not the simulators.

java - implement interfaces for threads

I am trying to "connect" two classes together, MyJFrame and MySerialPort, using the interface SerialPortListener, but I am clueless as how to do it. The reason I am doing this is because yesterday I had a problem assigning data from a serial port buffer to a global String (finalString), in the MySerialPort class. This string should be returned to MyJFrame where a label displays it. The problem was that my label would display finalString before anything
was assigned to finalString, since classes were running in different threads. I posted the question on the forum and received a suggestion to use interface to connect their threads, and I modified the code according. Where do I use the keyword implements SerialPortListener and how do I get the value?
SerialPortListener Interface code
public interface SerialPortListener {
void stringReveivedFromSerialPort(String s);
}
MyJFrame class code
public class MyJFrame extends JFrame{
public MySerialPorts msp = new MySerialPorts();
public MyJFrame(){
initComponents();//draws GUI components
initSerialPorts();//initializes serial ports
}
private void initSerialPorts(){
msp.getPortName();//gets serial port's name (in this example COM1)
msp.openPort();//opens the communication for port COM1
}
private String firmwareVersion(){
//This is the method I call when I want to get the Firmware Version
msp.getFirmwareVersion();//sends command to receive reply from serial device
lblFirmwareVersion.setText();//label that prints the firmware version String
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new MainJFrame().setVisible(true);
}
});
}
private JLabel lblFirmwareVersion;
}
MySerialPort class code
public class MySerialPort {
//this method is using the jSSC API (java simple serial connector)
//http://code.google.com/p/java-simple-serial-connector/
private SerialPort serialPort;
private int iBaudRate = SerialPort.BAUDRATE_57600;
private int iDataBits = SerialPort.DATABITS_8;
private int iStopBits = SerialPort.STOPBITS_1;
private int iParity = SerialPort.PARITY_NONE;
private String portName = "";
// private String finalString = "";
// private StringBuilder sbBuffer = new StringBuilder();
private List<SerialPortListener> portListeners = new ArrayList<SerialPortListenerInterface>();
public void addMyPortListener(SerialPortListener listener) {
portListeners.add(listener);
}
public void removeMyPortListener(SerialPortListener listener) {
portListeners.remove(listener);
}
public void getFirmwareVersion() {
sendPortCommand("<VersFV1A2>\r\n");
}
// public String returnFinalString() {
// return finalString;
// }
public void getPortName() {
String[] ports = SerialPortList.getPortNames();
portName = ports[0];
}
public void openPort() {
serialPort = new SerialPort(portName);
try {
if (serialPort.openPort()) {
if (serialPort.setParams(iBaudRate, iDataBits, iStopBits, iParity)) {
serialPort.addEventListener(new Reader(), SerialPort.MASK_RXCHAR
| SerialPort.MASK_RXFLAG
| SerialPort.MASK_CTS
| SerialPort.MASK_DSR
| SerialPort.MASK_RLSD);
} else {
//Error Message - Can't set selected port parameters!
serialPort.closePort();
}
} else {
//Error Message - Can't open port!
}
} catch (SerialPortException | HeadlessException ex) {
//Error Message - Can't open port! - Do nothing
}
}
private void sendPortCommand(String sSendPortCommand) {
if (sSendPortCommand.length() > 0) {
try {
serialPort.writeBytes(sSendPortCommand.getBytes());
} catch (Exception ex) {
//Error Message - Error occured while sending data!
}
}
}
private class Reader implements SerialPortEventListener {
private String sBuffer = "";
#Override
public void serialEvent(SerialPortEvent spe) {
if (spe.isRXCHAR() || spe.isRXFLAG()) {
if (spe.getEventValue() > 0) {
try {
//Read chars from buffer
byte[] bBuffer = serialPort.readBytes(spe.getEventValue());
sBuffer = new String(bBuffer);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
for (SerialPortListenerInterface listener : portListeners) {
listener.stringReveivedFromSerialPort(sBuffer);
}
}
});
// The following is the code I had prior to suggestion of using invokeLater instead of invokeAndWait
//
// sbBuffer.setLength(0);
//
// SwingUtilities.invokeAndWait(
// new Runnable() {
//
// #Override
// public void run() {
// sbBuffer.append(sBuffer);
// }
// });
//
// finalString = new String(sbBuffer);
} catch (Exception ex) {
}
}
}
}
}
}
Here's some code that you could add to your initSerialPorts() method, and which would open a dialog box displaying the text received from the serial port:
msp.addMyPortListener(new SerialPortListener() {
#Override
public void stringReveivedFromSerialPort(String s) {
JOptionPane.showMessageDialog(MyJFrame.this, s);
}
});
It creates an anonymous SerialPortListener instance, which displays a dialog box containing the received text as message, and adds it to your MySerialPort msp instance.
I believe that you want your MyJFrame class to implement SerialPortListener:
public class MyJFrame extends JFrame implements SerialPortListener {
/* blah */
#Override
public void stringReveivedFromSerialPort(String s) {
lblFirmwareVersion.setText(s);
}
/* blah */
}

Categories