I have two Telegram bots, written in Java.
First bot send some message every 10 min. (It works).
Second bot must read this sended message, and store it to txt file...
But problem is that the second bot don't see this message... He see messages only from USERS.
M - bot
YR - user
Chat image
Console result
Here says if
BotFather=>Bot=>Settings=>Group Privacy => Privacy mode disabled and >BotFather=>Bot=>Settings=>Allow Groups? => Groups are currently enabled
bots must see messages sent from one to another.
I did it, also bots was invited to new group with Administrator rights. Here code example (second bot):
public class TelegramBot extends TelegramLongPollingBot {
public final String BOT_TOKEN = "****************************";
public final String BOT_NAME = "*****************";
#Override
public void onUpdateReceived(Update update) {
long inChatID = 0;
int inMessID = 0;
String inText = "";
try { // from chanel
inChatID = update.getChannelPost().getChatId();
inText = update.getChannelPost().getText();
inMessID = update.getChannelPost().getMessageId();
} catch (Throwable t1) {};
try { // from chat
inChatID = update.getMessage().getChatId();
inText = update.getMessage().getText();
inMessID = update.getMessage().getMessageId();
} catch (Throwable t2) {};
System.out.println(inChatID);
System.out.println(inMessID);
System.out.println(inText);
}
#Override
public String getBotUsername() {
return BOT_NAME;
}
#Override
public String getBotToken() {
return BOT_TOKEN;
}
}
If I send any message like user, i getting in console ChatID, MessID, Text...
But if first bot send some message, i got nothing. Help me with this issue. Any suggestion where my mistake ?
I solved this issue by adding this two bots to channel with administrator rights.
It's don't works with GROUP CHAT.
Now i can see message sended from another bots.
But there is another problem: all messages sended by any bot in channel throws like channel message, with out Bot ID, Bot Name, etc...
So, I just can read message text, and parse it.
Related
Im doing a Discord Bot where i need to change the nickname of the user who send the message, for example: Person "A" send a message and i want to change his name to "B".
I have this code, but it doesnt work and i cant find why.
public void onGuildMessageReceived(GuildMessageReceivedEvent e) {
if(e.getAuthor().isBot()) return;
String[] args = e.getMessage().getContentRaw().split("\\s+");
System.out.println("lengh: " + args.length);
if(args[0].equalsIgnoreCase("!verify")) {
if(args.length == 2) {
Guild guild = e.getGuild();
//guild.getMember(e.getAuthor()).modifyNickname("asdsllslslsl").queue();
guild.modifyNickname(e.getMessage().getMember(), "pepeasd");
}
}
}
You're not queuing the RestAction you created. To queue it you'll need to add .queue() after the modifyNickname() method.
Read more about how RestAction and JDA work here: https://ci.dv8tion.net/job/JDA/javadoc/net/dv8tion/jda/api/requests/RestAction.html
I'm trying to send messages using the Discord JDA API, however whenever I send one, it sends it infinitely.
JDA Version: 4.2.1_255
What I've Tried:
Research the issue
Use GuildMessageReceivedEvent instead of MessageReceivedEvent
Pseudo-Code:
Guild server = e.getGuild();
Role role = server.getRolesByName("Java", false).get(0);
System.out.println(role);
for(Member members : server.getMembers()) {
if(members.getRoles().contains(role)) {
sendPrivateMessage(members.getUser(), "Hello <#!" + members.getId() + ">"); // Sends infinitely
}
}
sendPrivateMessage():
public void sendPrivateMessage(User user, String content) {
user.openPrivateChannel()
.flatMap(channel -> channel.sendMessage(content))
.queue();
}
You can try this
public void sendPrivateMessage(User user, String content) {
if (user.isBot()) return;
user.openPrivateChannel()
.flatMap(channel -> channel.sendMessage(content))
.queue();
}
if this code gets executed in the MessageReceivedEvent you may try adding
if(event.getAuthor().isBot()){
return;
}
so that it wont reply itself if you haven't already.
(If you want it to answer to other bots, you can also use the JDA, to get the selfUser and check if this event got executed by itself)
If thats not the case maybe you could tell us more about when it gets executed.
first post here. I've tried to look for a question I have but no luck so I figure I ask it myself.
I am working on 2 programs. An Android app in Java and a C# Windows Form App on windows. They are both simply scorekeeping calculators to keep track of the score of 2 players.
The goal of the 2 programs is to use a Bluetooth connection to send data back and forth between each other so that they are "synced". Android app is a client, c# app is a server (32feet library).
Using the Bluetooth Chat example on Android and some code i put together in VS, I managed to get the 2 programs to connect and send and receive data to each other, great!
But now my main goal is that I need to find out a way to take the incoming data coming from the Android app and change the appropriate labels/text on the windows app.
So for example:
on the Windows App, there are 2 Labels: one for Player1, one for Player2 that both say "10".
On the Android App, I have 2 buttons that separately subtract from either Player1 or Player2's score.
On the android app, if I touch the button that subtracts(-) 1 from Player1 it would be 9. I now want that change to apply to Player1's score label on the windows app, where it would also show 9.
I then want the same thing for Player2's score.
This is the best I can describe my goal, and I would like to know if it's possible, and if so, be pointed in the right direction.
Here is some provided code for what I have so far:
C# windows form app:
private void button1_Click(object sender, EventArgs e)
{
if (serverStarted == true)
{
updateUI("Server already started");
return;
}
if (radioButton1.Checked)
{
connectAsClient();
}
else
{
connectAsServer();
}
}
private void connectAsServer()
{
Thread bluetoothServerThread = new Thread(new ThreadStart(ServerConnectThread)); //creates new thread and runs "ServerConnectThread"
bluetoothServerThread.Start();
}
private void connectAsClient()
{
throw new NotImplementedException();
}
Guid mUUID = new Guid("fa87c0d0-afac-11de-8a39-0800200c9a66");
bool serverStarted = false;
public void ServerConnectThread()
{
serverStarted = true;
updateUI("Server started, waiting for client");
BluetoothListener blueListener = new BluetoothListener(mUUID);
blueListener.Start();
BluetoothClient conn = blueListener.AcceptBluetoothClient();
updateUI("Client has connected");
Stream mStream = conn.GetStream();
while (true)
{
try
{
//handle server connection
byte[] received = new byte[1024];
mStream.Read(received, 0, received.Length);
updateUI("Received: " + Encoding.ASCII.GetString(received));
byte[] sent = Encoding.ASCII.GetBytes("hello world");
mStream.Write(sent, 0, sent.Length);
}
catch (IOException exception)
{
updateUI("Client disconnected");
}
}
}
private void updateUI(string message)
{
Func<int> del = delegate ()
{
textBox1.AppendText(message + Environment.NewLine);
return 0;
};
Invoke(del);
}
}
Android App (snippet from the Bluetooth Chat example - i think this is the only relevant part):
/**
* Sends a message.
*
* #param message A string of text to send.
*/
private void sendMessage(String message) {
// Check that we're actually connected before trying anything
if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
Toast.makeText(getActivity(), R.string.not_connected, Toast.LENGTH_SHORT).show();
return;
}
// Check that there's actually something to send
if (message.length() > 0) {
// Get the message bytes and tell the BluetoothChatService to write
byte[] send = message.getBytes();
mChatService.write(send);
// Reset out string buffer to zero and clear the edit text field
mOutStringBuffer.setLength(0);
mOutEditText.setText(mOutStringBuffer);
}
}
You will want to have to add the clients to alist of streams for reference and also store the scores of each client on a list and then send the data coming from each client to the rest of the clients
so from the server youd have basically something like this
List<Stream> clients=new List<Stream>();
List<String> client_scores=new List<String>();
public void ServerConnectThread()
{
serverStarted = true;
updateUI("Server started, waiting for client");
BluetoothListener blueListener = new BluetoothListener(mUUID);
blueListener.Start();
BluetoothClient conn = blueListener.AcceptBluetoothClient();
updateUI("Client has connected");
Stream mStream = conn.GetStream();
clients.add(mStream);
client_scores.add(new Random().Next()+"");
int index_cnt = clients.IndexOf(mStream);
while (true)
{
try
{
//handle server connection
byte[] received = new byte[1024];
mStream.Read(received, 0, received.Length);
updateUI("Received: " + Encoding.ASCII.GetString(received));
client_scores[client_scores.FindIndex(ind=>ind.Equals(index_cnt))] = Encoding.ASCII.GetString(received);
byte[] sent = Encoding.ASCII.GetBytes("hello world");
mStream.Write(sent, 0, sent.Length);
foreach(Stream str in clients)
{
byte[] my_score = Encoding.ASCII.GetBytes(clients.ToArray()[index_cnt]+"");
str.Write(my_score, 0, my_score.Length);
}
}
catch (IOException exception)
{
updateUI("Client disconnected");
}
}
}
You can then serialize the data being sent in some sort of json so as to send multiple fields of data comfortably for example :
{
"data type": "score",
"source_id": "client_unique_id",
"data": "200"
}
On your displaying side,just get the values of (in our example case source_id and data) and display on a label
Created a bot and group. Added bot to the group(as admin) and starting trying posts. Through Url, it's smooth and successful. Started off exploring Telegram API(JAVA). Tests were on getUpdate and sendMessage methods.
I have generated TOKEN from telegram webapp(https://web.telegram.org).
Code snippet to getUpdates: yes, I have included bot ahead of the token.
TelegramBot bot = new TelegramBot("BOT_TOKEN");
GetUpdates getUpdates = new GetUpdates().limit(100).offset(0).timeout(0);
GetUpdatesResponse gur = bot.execute(getUpdates);
List<Update> list = gur.updates();
for(Update update : list) {
System.out.println(update.message());
}
Resonse is null.
code for sendMessage:
SendMessage request = new SendMessage(chatId, text)
.parseMode(ParseMode.HTML)
.disableWebPagePreview(true)
.disableNotification(true)
.replyToMessageId(1)
.replyMarkup(new ForceReply());
// sync
SendResponse sendResponse = bot.execute(request);
boolean ok = sendResponse.isOk();
Message message = sendResponse.message();
System.out.println(ok);
System.out.println(message);
Response is false and null.
I'm referring https://github.com/pengrad/java-telegram-bot-api#send-message
Help me understand the mistake. Thanks.
You need 109780439:AAJqs_w-4 format token, for instance:
TelegramBot bot = new TelegramBot("109780439:AAJqs_w-4");
This token can be obtained from #BotFather.
I am currently using map-api-2.1.0.jar and map-impl-2.1.0.jar for handling USSD string from mobile phone. This is working fine and user is receiving USSD response.
MapHandling Class
public class MapHandling implements MAPDialogListener,MAPServiceSmsListener,MAPServiceMobilityListener,MAPServiceCallHandlingListener,MAPSer viceSupplementaryListener{
#Override
public void onProcessUnstructuredSSRequest(ProcessUnstructuredSSRequest procUnstrReqInd)
{
try
{
logger.debug("dialogId: " +procUnstrReqInd.getMAPDialog().getLocalDialogId() + " USSD String:"+procUnstrReqInd.getUSSDString()+"MSISDN:"+procUnstrReqInd.getMAPDialog().getReceivedDestReference().getAddress());
} catch (Exception exp)
{
logger.error("USSD - error while loging ussd data ", exp);
}
ss7.request.UnstructuredSSRequest ussdRequest = new ss7.request.UnstructuredSSRequest(procUnstrReqInd);
Thread thr = new Thread(ussdRequest);
thr.start();
}
}
ss7.request.UnstructuredSSRequest Class
public class UnstructuredSSRequest extends SS7Operation implements Runnable {
ProcessUnstructuredSSRequest procUnstrReqInd;
public UnstructuredSSRequest(ProcessUnstructuredSSRequest procUnstrReqInd) {
this.procUnstrReqInd = procUnstrReqInd;
}
#Override
public void run() {
logger.debug("[" + refId + "] Sending USSD response");
sendUSSDResponse(validRequest);
}
private void sendUSSDResponse(boolean validRequest) {
MAPDialogSupplementary dialog = procUnstrReqInd.getMAPDialog();
USSDString ussdStrObj = MapProvider.getMAPParameterFactory().createUSSDString("Thank you for using CC service!");
dialog.addProcessUnstructuredSSResponse(procUnstrReqInd.getInvokeId(),procUnstrReqInd.getDataCodingScheme(), ussdStrObj);
dialog.close(false);
dialog.release();
}
}
Above code is running fine and I receive "Thank you for using CC service!" response when I dial USSD from my phone.
I want to change this into an interactive USSD handler, I want to take input from user when he dials USSD code instead of sending him response and closing the session.
Kindly help me how can I maintain a session for user and take his input.
I believe you are using Mobicents jSS7 project and above code is server side connected to HLR/MSC over SIGTRAN or E1.
If yes, you can see the sample code for server side at https://code.google.com/p/jss7/source/browse/map/load/src/main/java/org/mobicents/protocols/ss7/map/load/Server.java