Checking friendship in Tweepy - python

I am trying to find, do I follow someone or not. I realized that although it is written in official Tweepy document, I cannot use API.exists_friendship anymore. Therefore, I tried to use API.show_friendship(source_id/source_screen_name, target_id/target_screen_name) and as the document said it returns me friendship object. (<tweepy.models.Friendship object at 0x105cd0890>, <tweepy.models.Friendship object at 0x105cd0ed0>)
When I write screen_names = [user.screen_name for user in connection.show_friendship(target_id=someone_id)] it returns my_username and username for someone_id.
Can anyone tell me how can I use it properly? or is there any other method that simply returns me True/False because I just want to know do I follow him/her or not.

The method show_friendship returns a tuple which is a bit difficult to understand when you try to see if a specific user is following you and there is another way to see at once all the followers that are not following you. However, if you still want to check a single connection, I found that when you try the following:
status = api.show_friendship(A,B)
print(status[0].following, status[1].following)
If you get the output as True False it means that he/she is not following you. Other cases are:
False True = you are being followed by him/her.
False False = there is no connection between you two.
However, as I said above, you can check all the people that is not following you with a single snippet of code. As posted in another similar question, you can find the code at https://stackoverflow.com/a/45776597/4091473
Hope it helps!

Actually I do not like the answer but for now I used;
me = api.me()
user = api.get_user(username)
for f in user.friends():
if me.name in f.name:
print "FOLLOWING"
else:
print "NOT FOLLOWING"
I think there should be (and there is) an optimum solution (that's why I asked) about it and probably when my number of followings increases, the process of it will be longer. If you know better/optimum solution, please let me know.

i am using below code this works fine ..
if(api.show_friendship(source_screen_name='venky6amesh', target_screen_name='vag')):
print("the user is not a friend of ")
try:
api.create_friendship(j)
print('success')
except tweepy.TweepError as e:
print('error')
print(e.message[0]['code'])
else:
print("user is a friend of ",j)

def unfollow_non_followers():
friends = api.friends_ids()
me = api.me()
followers = api.followers_ids(me)
non_followers = [x for x in friends if x not in followers]
# unfollow all non-follow backs
for id in non_followers:
api.destroy_friendship(id)
# Display unfollowed user, pause for API limitations (valid or not?)
user = api.get_user(id)
print(f'No longer following {user.name}')
time.sleep(3)

Related

Marking an email as read python

I'd like to mark an email as read from my python code. I'm using
from exchangelib import Credentials, Account
my_account = Account(...)
credentials = Credentials(...)
to get access to the account. This part works great. I then get into my desired folder using this
var1 = my_account.root / 'branch1' / 'desiredFolder'
Again, this works great. This is where marking it as read seems to not work.
item = var1.filter(is_read=False).values('body')
for i, body in enumerate(item):
#Code doing stuff
var1.filter(is_read=False)[i].is_read = True
var1.filter(is_read=False)[i].save(updated_fields=['is_read'])
I've tried the tips and answers from this post Mark email as read with exchangelib, but the emails still show as unread. What am I doing wrong?
I think you the last line of code that you save() do not work as you think that after you set is_read of unread[i] element to True, this unread[i] of course not appear in var1.filter(is_read=False)[i] again, so you acttually did not save this.
I think this will work.
for msg in my_account.inbox.filter(is_read=False):
msg.is_read = True
msg.save(updated_fields=['is_read'])
To expand on #thangnd's answer, the reason your code doesn't work is that you are calling .save() on a different Python object than the object you are setting the is_read flag on. Every time you call var1.filter(is_read=False)[i], a new query is sent to the server, and a new Python object is created.
Additionally, since you didn't specify a sort order (and new emails may be incoming while the code is running), you may not even be hitting the same email each time you call var1.filter(is_read=False)[i].

Tweepy Check Blocked User?

Is there a way to check if the user is blocked like an is_blocked method? The way I have it set up right now is to get a list of my blocked users and comparing the author of a Tweet to the list, but it's highly inefficient, as it constantly runs into the rate limit.
Relevent Code:
blocked_screen_names = [b.screen_name for b in tweepy.Cursor(api.blocks).items()]
for count, tweet in enumerate(tweepy.Cursor(api.search, q = query, lang = 'en', result_type = 'recent', tweet_mode = 'extended').items(500)):
if tweet.user.screen_name in blocked_screen_names:
continue
No, you'll have to do that the way you're currently doing it.
(Also, just a side note, you're better off checking your blocked users via their account ID rather than their screen name, because this value will not change, whereas a user's screen name can)
For future reference, just check the Twitter API documentation, where you can get the answer for something like this straight away :) save yourself the waiting for someone to answer it for you here!
You'll notice that both the documentation for V1 and V2 do not contain an attribute as you have described:
V1 User Object:
https://developer.twitter.com/en/docs/twitter-api/v1/data-dictionary/object-model/tweet
V2 User Object:
https://developer.twitter.com/en/docs/twitter-api/data-dictionary/object-model/user

how to validate values in array and do actions python whatsapp framework

I am newbie learning python, I need a little help in whatsapp framework in github but that's python programming where my knowledge is limited. here you can see two things:
message.text ( here is stored the whatsapp message, so i can create commands)
message.conversation (here you can get the groupid or phone number of the sender)
the example code:
# modules/hi_module.py
from app.mac import mac, signals
#signals.message_received.connect
def handle(message):
if message.text == "hi":
mac.send_message("Hello", message.conversation)
# Can also send media
#mac.send_image("path/to/image.png", message.conversation)
#mac.send_video("path/to/video.mp4", message.conversation)
i want to limit my commands like that "hi" to work only in three groups allowed by me, i am thinking in an array where this is stored. So i am thinking in an idea like that
groupIds = { "group": "123456789#whatsapp.net", "group": "123458754#whatsapp.net",}
if "hi" in message.text:
validategroup()
#do something
else:
#print("you are not allowed to do this command")
def validategroup:
if groupIds in message.conversation:
validation = true
else:
validation = false
I am stuck at this part, I don't know how to code correctly the method and how to return and allow command or deny. please help me to learn
I think you can not do like this
if groupIds in message.conversation:
As groupIds is dic and you can not find complete dic. you should use the value of the key to find in message.conversation.
One more I want to check is message.conversation get string or list..?
Thanks
Your BOOLEAN values must begin with a Capital Letter ( i.e. True or False ).

Python unittest, results vary depending on print statement

I'm mildly confused. I'm testing a django application with python's unittest library. All of a sudden, after running my tests with 100 % success for some minutes, suddenly an error appears. Ok I thought, I must have just added some stupid syntax error. I started looking at the test and then my code, I then tried to print out the results which are being compared with assertEqual before they are compared. Suddenly if I do that, the test runs!!! :o
Why is this? has anyone experienced this before. I swear, the only change I made was adding a print statement inside my test function. I'll post this function before and after
Before (Fails)
def test_swap_conditionals(self):
"""
Test conditional template keys
"""
testStr = "My email is: {?email}"
swapStr = self.t.swap(testStr)
# With email
self.assertEqual(swapStr, "My email is: john#baconfactory.com")
# Without email
self.t.template_values = {"phone" : "00458493"}
swapStr = self.t.swap(testStr)
self.assertEqual(swapStr, "My email is: ")
After (Success)
def test_swap_conditionals(self):
"""
Test conditional template keys
"""
testStr = "My email is: {?email}"
swapStr = self.t.swap(testStr)
print(swapStr) #diff here
# With email
self.assertEqual(swapStr, "My email is: john#baconfactory.com")
# Without email
self.t.template_values = {"phone" : "00458493"}
swapStr = self.t.swap(testStr)
self.assertEqual(swapStr, "My email is: ")
It looks like there is some external reason.
What you can check:
Rerun the test several times under the same conditions. Is it always failing or passing? Or is it a 'flipper' test? This might be caused by timing issues (although unlikely).
Put the test in its own class, so there are no side effects from other unit tests.
If the test in its own test class was passing the reason is a side effect by:
other unit tests
startup/teardown functionality
Ok well embarrassing, but this was completely my fault. The swap function was looking up every conditional template variable on the line and then iterating over that list one conditional template variable at a time, so either it missed keys it already had or it got lucky and it happened to hit that key.
Example
line: "This is my {?email}, and this is my {?phone}"
finds:
[{?email}, {?phone}]
iterates over [{?email}, {?phone}]
1. {?email}
key being compared = phone : '00549684'
It has phone as a key but it completely disregards it and does not swap it out because
it's just holding {?email} so it simply returns "".
I'm sincerely sorry to waste all your time here. Thanks for good answers. I am refactoring the code now for the better, and definitely taking a coffee break :D

Change python command to subtract value instead of add in MYSQL

Just got one other question for my python plugin.
Here is the code:
def cmd_give(self, data, client=None, cmd=None):
"""
^3<player> <money> - Give someone however much money you want.
"""
input = self._adminPlugin.parseUserCmd(data)
if not data:
client.message('^7 correct syntax is !give <player> <money>')
return False
else:
if len([x for x in data if x.isspace()]) < 1:
client.message('^7 correct syntax is !give <player> <money>')
return False
else:
input_data = data.split(' ',1)
scname = input_data[0]
ammount = int(input_data[1])
sclient = self._adminPlugin.findClientPrompt(scname, client)
if not sclient: return False
self.earn_money(sclient, ammount)
return True
Now this obviously adds the value given in the command to the user inputting into mysql.
I'm also wanting a command to subtract any value given in the command as well.
So this command above is a give and I also want a take.
My problem is I don't know what the change is to minus the amount off the value input instead of adding.
Hope someone can help,
Thanks guys.
Without modifying the function that does the actual addition, the suggestion by Rob Watts in a comment will work:
ammount = -int(input_data[1])
You can either create a new function, cmd_take, and do that there, or have a more general function (cmd_transaction?) that takes an extra argument (eg give) and has the appropriate logic:
if not give:
ammount = -int(input_data[1])
In the first case, it would be good practice to extract most of the code to a helper function, to avoid repetition, but if you don't know python and this is just a one time thing, having a cmd_take function that is exactly like command_give, except for that one line, is the simplest solution.

Categories

Resources