How to get followers and following list screen names (Twitter4J)? - java

I am trying to get my followers and following list via Twitter 4J.
I pass the configuration builder from the main method as a parameter to the method.
Here is the code:
try {
Twitter twitter = new TwitterFactory().getInstance();
long cursor = -1;
IDs ids;
System.out.println("Listing following ids.");
do {
if (0 < args.length) {
ids = twitter.getFriendsIDs(args[0], cursor);
} else {
ids = twitter.getFriendsIDs(cursor);
}
for (long id : ids.getIDs()) {
System.out.println(id);
}
} while ((cursor = ids.getNextCursor()) != 0);
System.exit(0);
} catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to get friends' ids: " + te.getMessage());
System.exit(-1);
}
So far this only returns IDS but it does not return the screen name of the followers. Does anyone have any idea? I am working in Java and printing to the terminal.
Thanks.

String twitterScreenName = twitter.getScreenName();
PagableResponseList<User> statuse = twitter.getFollowersList(twitterScreenName, -1);
for (User follower : statuse) {
System.out.println(follower.getName());
}

Related

Get data from query result and set them into list of objects in Spring Boot

I have an api to upload a file and save it's columns to database there is no problem for here. But i have to get some properties from database and set them into my list object and save all of them together. But when i trying to use foreach to set those results to my model i got same result for every one of them. Query result comes as list. I couldn't seperate them.
For example row[0] has 4 properties. and i couldn't reach row[0]'s third parameter. And set it to my model.
I want to reach that properties all for every coming list. How can i do it with foreach.
I want to set them all separately.
Query query2 = em.createNativeQuery(selectQuery);
List<Object[]> rows = new ArrayList<>();
try {
rows = query2.getResultList();
} catch (Exception e) {
e.printStackTrace();
}
for (DiscountFile discountFileModel : discountFileList) {
for (Object[] row : rows) {
if (row[0] != null) {
discountFileModel.setBtHesapId(row[0].toString());
} else {
discountFileModel.setBtHesapId(null);
}
if (row[1] != null) {
discountFileModel.setOzelKod(row[1].toString());
} else {
discountFileModel.setOzelKod(null);
}
if (row[2] != null) {
discountFileModel.setAktarildi(row[2].toString());
} else {
discountFileModel.setAktarildi(null);
}
if (row[3] != null) {
discountFileModel.setBtProductSerialNo(row[3].toString());
} else {
discountFileModel.setBtProductSerialNo(null);
}
if (row[4] != null) {
discountFileModel.setBtTmsAboneId(row[4].toString());
} else {
discountFileModel.setBtTmsAboneId(null);
}
if (row[5] != null) {
discountFileModel.setBtCrmHesapNo(row[5].toString());
} else {
discountFileModel.setBtCrmHesapNo(null);
}
discountFileModel.setBireyselKurumsal(listeTipi);
iDiscountFile.saveAll(discountFileList);
}
}

getting first level of categorisation from Notes view

I have a categorized Notes view, let say the first categorized column is TypeOfVehicle the second categorized column is Model and the third categorized column is Manufacturer.
I would like to collect only the values for the first category and return it as json object:
I am facing two problems:
- I can not read the value for the category, the column values are emptry and when I try to access the underlying document it is null
the script won't hop over to the category/sibling on the same level.
can someone explain me what am I doing wrong here?
private Object getFirstCategory() {
JsonJavaObject json = new JsonJavaObject();
try{
String server = null;
String filepath = null;
server = props.getProperty("server");
filepath = props.getProperty("filename");
Database db;
db = utils.getSession().getDatabase(server, filepath);
if (db.isOpen()) {
View vw = db.getView("transport");
if (null != vw) {
vw.setAutoUpdate(false);
ViewNavigator nav;
nav = vw.createViewNav();
JsonJavaArray arr = new JsonJavaArray();
Integer count = 0;
ViewEntry tmpentry;
ViewEntry entry = nav.getFirst();
while (null != entry) {
Vector<?> columnValues = entry.getColumnValues();
if(entry.isCategory()){
System.out.println("entry notesid = " + entry.getNoteID());
Document doc = entry.getDocument();
if(null != doc){
if (doc.hasItem("TypeOfVehicle ")){
System.out.println("category has not " + "TypeOfVehicle ");
}
else{
System.out.println("category IS " + doc.getItemValueString("TypeOfVehicle "));
}
} else{
System.out.println("doc is null");
}
JsonJavaObject row = new JsonJavaObject();
JsonJavaObject jo = new JsonJavaObject();
String TypeOfVehicle = String.valueOf(columnValues.get(0));
if (null != TypeOfVehicle ) {
if (!TypeOfVehicle .equals("")){
jo.put("TypeOfVehicle ", TypeOfVehicle );
} else{
jo.put("TypeOfVehicle ", "Not categorized");
}
} else {
jo.put("TypeOfVehicle ", "Not categorized");
}
row.put("request", jo);
arr.put(count, row);
count++;
tmpentry = nav.getNextSibling(entry);
entry.recycle();
entry = tmpentry;
} else{
//tmpentry = nav.getNextCategory();
//entry.recycle();
//entry = tmpentry;
}
}
json.put("data", arr);
vw.setAutoUpdate(true);
vw.recycle();
}
}
} catch (Exception e) {
OpenLogUtil.logErrorEx(e, JSFUtil.getXSPContext().getUrl().toString(), Level.SEVERE, null);
}
return json;
}
What you're doing wrong is trying to treat any single view entry as both a category and a document. A single view entry can only be one of a category, a document, or a total.
If you have an entry for which isCategory() returns true, then for the same entry:
isDocument() will return false.
getDocument() will return null.
getNoteID() will return an empty string.
If the only thing you need is top-level categories, then get the first entry from the navigator and iterate over entries using nav.getNextSibling(entry) as you're already doing, but:
Don't try to get documents, note ids, or fields.
Use entry.getColumnValues().get(0) to get the value of the first column for each category.
If the view contains any uncategorised documents, it's possible that entry.getColumnValues().get(0) might throw an exception, so you should also check that entry.getColumnValues().size() is at least 1 before trying to get a value.
If you need any extra data beyond just top-level categories, then note that subcategories and documents are children of their parent categories.
If an entry has a subcategory, nav.getChild(entry) will get the first subcategory of that entry.
If an entry has no subcategories, but is a category which contains documents, nav.getChild(entry) will get the first document in that category.

How verify if a member is admin?

I'm working on a bot for supergroups.
How I can verify if member is admin?
my lib:org.telegram 4.2 https://core.telegram.org/bots/api
I tried with ChatMember, GetChatAdministrators and SendMessage methods but I have no idea how insert parameters because they don't ask them but they have only .get option (null respose). Only GetChatAdministrators permit a .set method for ChatID but it give error
GetChatAdministrators getadmin = new GetChatAdministrators().setChatId(ChatIDSupergroup);
ArrayList<ChatMember> s = null;
try {
s = getadmin.deserializeResponse(null); //Unable to deserialize response
} catch (TelegramApiRequestException e) {
e.printStackTrace();
}
ChatMember member = new ChatMember(); //There are only get options
String status=member.getStatus(); //null
I had a same problem but I couldn't find an answer from anywhere. Then I tried myself and finally today I found the following solution:
public List<ChatMember> getChatAdministrators(Long chatId){
List<ChatMember> chatAdministrators = Collections.emptyList();
try {
chatAdministrators = execute(new GetChatAdministrators(String.valueOf(chatId)));
} catch (TelegramApiException e) {
e.printStackTrace();
}
return chatAdministrators;
}
This method returns list of administrators of telegram groups, supergroups or channels.
function adminCheck( id, chat_id ) {
var bAdminCheck = false;
var name = "";
var aChatMember = getChatAdministrators( chat_id );
var contents = JSON.parse( aChatMember );
var i = 0;
while( !bAdminCheck && ( i < contents.result.length ) ) {
if( id == contents.result[i].user.id ) {
bAdminCheck = true;
}
i++;
}
return {
AdminCheck: bAdminCheck,
};
}
Available methods
source:
https://core.telegram.org/bots/api#available-methods
getChatAdministrators
Use this method to get a list of administrators in a chat. On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned.

ParseQuery Array to lowercase before search

I have issue with searching trough ParseQuery Array.
I need case insensitive search, so i need to convert my array to lowercase.
I tried query.whereMatches and query.whereContains without success.
My guess is to make new method that would convert all data from ParseQuery to lowercaseString Array.
Am i right with this one?
Here's the example code for setting search result list:
private void setList(boolean hardRefresh) {
// stop any ongoing progress dialog
cancelProgressDialog();
reloadTags();
reloadContents();
ParseQuery<Note> query = Note.getQuery()
.fromLocalDatastore()
.orderByDescending("date");
String searchStr = searchText.getText().toString().toLowerCase();
if (!searchStr.isEmpty()) {
query.whereMatches(Note.FIELD_DETAIL, searchStr);
}
try {
mNotes = query.find();
if (adapter == null) {
adapter = new ListAdapter();
notesGridView.setAdapter(adapter);
} else {
adapter.notifyDataSetChanged();
}
} catch (ParseException e) {
e.printStackTrace();
}
For case insensitive search try like this :
if (!searchStr.isEmpty()) {
query.whereMatches(Note.FIELD_DETAIL, searchStr,"i");
}

Twitter4J: Get more than 1 tweet from a user

I'm trying to get a list of recent statuses from each user on a persons list of followers. I've got the following to get the users...
IDs list = twitter.getFriendsIDs(0);
for(long ID : list.getIDs()){
twitter4j.User TW_user = twitter.showUser(ID);
}
All I can get from this is getStatus() which is their most recent status. getHomeTimeline() is also insufficient as I need a list of recent tweets from each user. Is there anyway I can achieve this using Twitter4J?
I was just trying to find this answer myself. I had decent success using the getUserTimeline method. Looks like you're trying to look up a list of friend IDs, so this method below should take the long[] and spit out all the user statuses. lookupUsers also accepts a String[] of screen names if you want to look users up that way instead.
public static void lookupUsers(long[] usersList) {
try {
Twitter twitter = new TwitterFactory().getInstance();
ResponseList<User> users = twitter.lookupUsers(usersList);
Paging paging = new Paging(1, 100);
List<Status> statuses;
for (User user : users) {
statuses = twitter.getUserTimeline(user.getScreenName(), paging);
System.out.println("\nUser: #" + user.getScreenName());
for (Status s : statuses) {
System.out.println(s.getText());
}
}
} catch (TwitterException e) {
e.printStackTrace();
}
}
Alex's answer is close, but will only get you 100 tweets per user. The following will get you all (or at least the API's max limit):
IDs list = twitter.getFriendsIDs(0);
for(long ID : list.getIDs()) {
Status[] tweets = getAllTweets(twitter, ID);
System.out.println(ID + ": " + tweets.length);
}
Status[] getAllTweets(Twitter twitter, long userId)
{
int pageno = 1;
List statuses = new ArrayList();
while (true)
{
try
{
int size = statuses.size();
Paging page = new Paging(pageno++, 100);
statuses.addAll(twitter.getUserTimeline(userId, page));
if (statuses.size() == size)
break;
}
catch (TwitterException e)
{
e.printStackTrace();
}
}
return (Status[]) statuses.toArray(new Status[0]);
}

Categories

Resources