Not everyone on Twitter is interested in a friendly conversation. Some people are just there for mischief and harassment. Let's look at how we can use Tweepy to block and mute accounts.
Preparation
As with the examples before, we need the user authentication tokens to work on behalf of that user. We use the V2 endpoints for this post:
importtweepyimportosfromdotenvimportload_dotenvload_dotenv()# read keys from .envapi_key=os.getenv('api-key')api_secret=os.getenv('api-key-secret')client_id=os.getenv('client-id')client_secret=os.getenv('client-secret')user_token=os.getenv('access-token')user_token_secret=os.getenv('access-token-secret')bearer_token=os.getenv('bearer-token')client=tweepy.Client(bearer_token=bearer_token,consumer_key=api_key,consumer_secret=api_secret,access_token=user_token,access_token_secret=user_token_secret,wait_on_rate_limit=True)
Get the user id from a screen name
Most methods we use in this post require the user id for an account. If you have a screen name, you can use this code to find the user id:
# find user id by usernameuser_to_mute="BILD"response=client.get_user(username=user_to_mute)user=response.dataprint(f"id of user '@{user_to_mute}': {user.id}")
id of user '@BILD': 9204502
Mute an account
Muted accounts can still see what you tweet, but you do no longer see what they tweet and retweet. We can use the method mute() to mute an account:
# get a list of all muted usersmuted=[]forresponseintweepy.Paginator(client.get_muted,max_results=1000,limit=10):foruserinresponse.data:muted.append(f"@{user.username} - {user.name} - {user.id}")print("Muted users:")forentryinmuted:print(entry)
Muted users: @BILD - BILD - 9204502
Unmute an account
If we no longer want to mute an account, we can use the method unmute():
# get a list of all blocked usersblocked=[]forresponseintweepy.Paginator(client.get_blocked,max_results=1000,limit=10):foruserinresponse.data:blocked.append(f"@{user.username} - {user.name} - {user.id}")print("Blocked users:")forentryinblocked:print(entry)
Blocked users: @BILD - BILD - 9204502
Unblock an account
Should you have blocked the wrong account, you can use the method unblock() to fix it:
# unblock a userresult=client.unblock(target_user_id=user.id)print(f"user blocked? {result.data['blocking']}")
user blocked? False
Next
Blocking and muting are important activities to keep a positive Twitter experience. With the trolls out of our sight, we can next week look at the more positive side of interactions.