Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Creating a Twitter Bot with Phoenix
Kevin Expósito
Kevin Expósito

Posted on • Edited on

     

Creating a Twitter Bot with Phoenix

I started this blog in order to learn how to use Twitter API and also because i love going to the cinema 🙌. Im from Uruguay 🇺🇾, and here we have a cinema called "Movie Center". After checking their request, I started to investigate what we can get from them


Investigation 🕵️

After checking their request I found out that I can use that information for the Twitter bot.

Image description

Image description

Image description

Image description


Creating the app 👨‍💻

Let’s start by creating our Phoenix app

mix phx.new movies_uycdmovies_uymix ecto.createiex-S mix phx.server
Enter fullscreen modeExit fullscreen mode

Now Im going to add the following dependencies that are needed for the bot:

# mix.exsdefpdepsdo[{:finch,"~> 0.13"},{:oauther,"~> 1.1"},{:extwitter,"~> 0.12"},{:oban,"~> 2.13"}]end
Enter fullscreen modeExit fullscreen mode
  • Finch for doing request to the "Movie Center" API.
  • ExTwitter it's a Twitter Client for using Twitter API
  • Oban for creating jobs that run whenever we want (in our case once a day)

After adding this don't forget to runmix deps.get.


Config Finch

Let’s configure Finch by adding this, note that you can follow this from the Finch repo too.

# lib/movies_uy/application.exdefstart(_type,_args)dochildren=[...{Finch,name:MoviesUyFinch}]end
Enter fullscreen modeExit fullscreen mode


Config ExTwitter 🧵

# config/config.exsconfig:extwitter,:oauth,[consumer_key:System.get_env("TWITTER_CONSUMER_KEY"),consumer_secret:System.get_env("TWITTER_CONSUMER_SECRET"),access_token:System.get_env("TWITTER_ACCESS_TOKEN"),access_token_secret:System.get_env("TWITTER_ACCESS_TOKEN_SECRET")]
Enter fullscreen modeExit fullscreen mode

Getting Movies 🎬

Let's add the following code that will search for all the movies from the Movie Center API.

# lib/movies_uy/movie_center.exdefmoduleMoviesUy.MovieCenterdorequireLoggerdeffetch_moviesdomovie_url="https://api.movie.com.uy/api/billboard/cinema/weekly?nextReleases=false"request=Finch.build(:get,movie_url)|>Finch.request(MoviesUyFinch)with{:ok,%Finch.Response{body:data}}<-request,%{"items"=>movies}<-Jason.decode!(data)domovies|>Enum.map(fn%{"content"=>%{"title"=>title,"id"=>id,"urlSlug"=>slug}}}->"#{title} - https://www.movie.com.uy/movie/#{id}/#{slug}"end)else_->Logger.error"Error!"endendend
Enter fullscreen modeExit fullscreen mode

You can also check if this is working correctly by running the following line on your iex

$iex> MoviesUy.MovieCenter.fetch_movies# this should show all the movies from Movie center API

Using ExTwitter 🧵

Now is time to build the messages and post them on Twitter using ExTwitter.

What Im going to do is create a tweet that contains the current date, and the comments of this twitter will be the movies with their current url on Movie Center.

# lib/movies_uy/movie_center.exdefmoduleMoviesUy.MovieCenterdorequireLoggerdeffetch_moviesdomovie_url="https://api.movie.com.uy/api/billboard/cinema/weekly?nextReleases=false"request=Finch.build(:get,movie_url)|>Finch.request(MoviesUyFinch)with{:ok,%Finch.Response{body:data}}<-request,%{"items"=>movies}<-Jason.decode!(data),%ExTwitter.Model.Tweet{id:tweet_id}<-post_message()domovies|>Enum.map(&post_thread_message(&1,tweet_id))elseerror->Logger.errorerrorendenddefppost_thread_message(%{"content"=>%{"title"=>title,"id"=>id,"urlSlug"=>slug}},tweet_id)do"#{title} - https://www.movie.com.uy/movie/#{id}/#{slug}"|>ExTwitter.update(in_reply_to_status_id:tweet_id)enddefppost_messagedo%Date{day:day,month:month,year:year}=Date.utc_today"Cartelera de Movie Center del#{day}/#{month}/#{year}"|>ExTwitter.updateendend
Enter fullscreen modeExit fullscreen mode

We can run this using the same function as before and we should be able to see that is posting correctly on Twitter.

Image description


Config Oban 📅

It’s time to use Oban, this will allow us to create a worker that runs our code whenever we want, in our case once a day! Lets config Oban (you can also read the docs).

$mix ecto.gen.migration add_oban_jobs_table
Enter fullscreen modeExit fullscreen mode

Then open the generated migration and update it:

defmoduleMoviesUy.Repo.Migrations.AddObanJobsTabledouseEcto.MigrationdefupdoOban.Migrations.up(version:11)end# We specify `version: 1` in `down`, ensuring that we'll roll all the way back down if# necessary, regardless of which version we've migrated `up` to.defdowndoOban.Migrations.down(version:1)endend
Enter fullscreen modeExit fullscreen mode

And finally lets run this

$mix ecto.migrate
Enter fullscreen modeExit fullscreen mode

Lets add this

#config/config.exsconfig:movies_uy,Oban,repo:MoviesUy.Repo,plugins:[Oban.Plugins.Pruner,{Oban.Plugins.Cron,crontab:[{"@daily",MoviesUy.DailyWorker,max_attempts:1},]}],queues:[default:10]
Enter fullscreen modeExit fullscreen mode
# lib/my_app/application.exdefstart(_type,_args)dochildren=[...{Oban,Application.fetch_env!(:movies_uy,Oban)}]end
Enter fullscreen modeExit fullscreen mode
# lib/movies_uy/workers/daily_worker.exdefmoduleMoviesUy.DailyWorkerdouseOban.Worker,queue::default@implOban.Workerdefperform(_)doMoviesUy.MovieCenter.fetch_movies()endend
Enter fullscreen modeExit fullscreen mode

Thats it! you can see this Twitter bot working visiting:https://twitter.com/movies_uy

Note: you can also create just a mix app and this guide will work too. I usedphx because Im planning to do another thing in the future with it


Things we used here:


Visit the bot:

Twitter bot:https://twitter.com/movies_uy

The code:

https://github.com/kexposito/movies-uy

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

HI! My name is Kevin ExpositoI consider myself self-taught, a teaching enthusiast and a Vim lover.My daily routine consists of listening to the radio, drinking mate and coding, usually simultaneous
  • Location
    Montevideo, Uruguay
  • Joined

More fromKevin Expósito

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp