📜 ⬆️ ⬇️

Automatic sending of announcements to Twitter

Recently, when working on a project on Django, it was necessary to automatically send a twitter header and a short link for published articles on behalf of the user to Twitter.

As it turned out, this is done quite easily.


I immediately decided not to reinvent the wheel and use one of the available libraries to work with Twitter. Twython looked to me the most . Import it into models.py:
')
Copy Source | Copy HTML import twython.core as twython
  1. Copy Source | Copy HTML import twython.core as twython

Here is a simplified publication model. I left only the minimum fields:

Copy Source | Copy HTML
  1. class Post (models.Model):
  2. title = models.CharField (max_length = 100 )
  3. media = models.TextField ()
  4. published = models.BooleanField (default = False)
  5. tweeted = models.BooleanField (default = False, editable = False)
  6. def __unicode__ (self):
  7. return u '% s' % self .title
  8. @ models.permalink
  9. def get_absolute_url (self):
  10. return ( 'news.views.news_view' , [ str ( self .id)])

The model has two fields - published in order not to tweet drafts and tweeted, so that each post is announced only once.

Now the process of sending the announcement:

Copy Source | Copy HTML
  1. def post_to_twitter (sender, instance, ** kwargs):
  2. "" " <br/> We send an announcement in TWI if the post is published but not yet closed <br/> " ""
  3. if instance.published and not instance.tweeted:
  4. try :
  5. twitter = twython.setup (username = "TWITTER_USER" , password = "TWITTER_PASSWORD" )
  6. long_url = "http: //% s% s" % (Site.objects.get_current (), instance.get_absolute_url ())
  7. short_url = twitter.shortenURL (long_url)
  8. twi_message = instance.title + "" + short_url
  9. try :
  10. twitter.updateStatus (twi_message)
  11. Post.objects. filter (pk = instance.pk) .update (tweeted = True)
  12. except TwythonError:
  13. pass
  14. except AuthError:
  15. pass

It is logical to hang up the twittering process on the post_save event:

post_save.connect(post_to_twitter, sender=Post)


That's all. You can add any kind of usefulness to taste, but in this form it works quite well.

Source: https://habr.com/ru/post/88811/


All Articles