Python Twitter(X) Bot: A Simple Bot to Automatically Tweet Weather Updates on Twitter🌦️

Elif Tabanca
CodeX
Published in
7 min readJun 20, 2024
Photo by Kelly Sikkema on Unsplash

Hello! For those who enjoy coding, seeing the live output of your code is quite motivating; at least it is for me 🙂. In this article, I wanted to create a simple weather bot using Python. This bot will call a weather API to retrieve weather information and automatically tweet this information on a Twitter account.🌈

I chose to call the weather API due to the current hot weather in Istanbul, but you can also call APIs for news, exchange rates, sports scores, movie data, and many other types of information. If desired, AI integration can also be done. In my future posts, I will explain how to use AI APIs as well.

Steps to Follow

  1. Creating a Twitter Developer Account (link)
  2. Signing Up for a Weather API (You can use any free API provider; I used this site)
  3. Installing Required Python Libraries
  4. Creating and Running the Bot

1. Creating a Twitter Developer Account

First, you need to create a Twitter Developer account. After creating the developer account, you’ll need to create a project and generate the following API keys:

  • API Key
  • API Secret Key
  • Access Token
  • Access Token Secret
  • Bearer Token

Note: These details are crucial parts that authenticate your application, and you should store them securely. In my code, I’ve stored these details in the config.py file and added it to the gitignore file to prevent sharing on GitHub.

2. Registering for a Weather API

To get weather data, I used the WeatherAPI site to get an API key. However, many other free sites are available. After signing up and getting your API key, keep this key secure as well.

3. Installing Required Python Libraries

Importing Libraries: First, we include the necessary Python libraries in our code such as tweepy, requests, and schedule.

4. Creating and Running the Bot

  1. Importing Libraries: First, we include the necessary Python libraries in our code such as tweepy, requests, and schedule
  • import tweepy: This library allows us to use ready-made functions for interacting with the Twitter API. It makes our work easier, but it’s not mandatory; we can also write our own functions provided by tweepy.
  • import requests: This library is used to send and receive HTTP requests, essential for interacting with external APIs.
  • import schedule: This library is used to schedule and manage specific tasks. For example, it’s necessary for scheduling automatic processes. I haven’t added this to my code yet, but in my next post, I’ll share a short code snippet on how we can automate sharing.
  • from config import *: All variables from the config.py file are included in our code. I entered important information like API keys that need to be stored securely in this file.

2. Setting Up Twitter API Access: These steps are necessary for accessing your Twitter account and performing certain operations. For the most reliable information, always refer to the library’s own documentation. For the tweepy library, you can find the methods we use here. I created a my_client instance from the Client class to post tweets and included the required authentication keys (bearer_token, consumer_key, consumer_secret, access_token, access_token_secret) obtained from Twitter Dev.

3. config.py: Our API keys are stored in this file.

4.Functions: I wrote separate functions for each step to ensure the code is clean and understandable. Each function is designed to return meaningful output.

  • get_weather Function: Sends an HTTP request to WeatherAPI to get weather data for the specified city.
  • create_weather_info_text Function: Creates the tweet text using the desired data from the returned JSON file.
  • tweet_post Function: Posts the created tweet text on Twitter.

By following these steps, you can create a simple weather bot that automatically fetches weather information and posts it on Twitter. This project not only helps you improve your Python programming skills but also allows you to interact with real-world data using the Twitter API. In my next post, I will explain how to further develop this bot by scheduling automatic posts and adding AI integration.

Feel free to reach out if you have any questions or would like to add anything!

Sources: Tweepy DocumentationWebsite, X Developer Platform

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

Python ile Twitter(X) Botu: Twitter’a Otomatik Hava Durumu Tweetleri Atan Basit Bir Bot🌦️

Merhaba! Kodlama ile uğraşanlar için yazılan kodun çıktısını görmek oldukça motive edicidir, en azından benim için öyle 🙂 Bu yazıda, Python kullanarak basit bir hava durumu botu oluşturmak istedim. Bu bot, hava durumu API’sini çağırarak hava durumu bilgilerini alacak ve bu bilgileri bir Twitter hesabında otomatik olarak tweet olarak paylaşacak.🌈

Ben bu sıcak havaların gündemine uygun olarak hava durumu için bir API çağrısı yaptım (ben sadece istanbul), ancak haberler, döviz kurları, spor skorları ve film bilgileri verileri gibi birçok farklı API çağrısı da yapılabilir. İstenirse yapay zeka entegrasyonu da yapılabilir. İleriki yazılarımda yapay zeka API lerini kullanarak neler yapılabileceğini de elimden geldiğince anlatmaya çalışacağım.

Gerekli Adımlar

  1. Twitter Geliştirici Hesabı Oluşturma (link)
  2. Hava Durumu API’si İçin Kayıt Olma (Herhangi bir free API sağlayan site tercih edilebilir ben bu siteyi kullandım)
  3. Gerekli Python Kütüphanelerini Yükleme
  4. Botu Oluşturma ve Çalıştırma

1. Twitter Geliştirici Hesabı Oluşturma

Öncelikle bu linkten bir Twitter Developer hesabı oluşturmanız gerekiyor. Geliştirici hesabını oluşturduktan sonra bir proje ve API anahtarları oluşturmanız gerekecek:

  • API Key
  • API Secret Key
  • Access Token
  • Access Token Secret
  • Bearer Token

Not: Bu bilgiler, uygulamanızın kimlik doğrulamasını sağlayan önemli parçalardır ve bunları güvenli bir şekilde saklamalısınız. Benim kodumda bu bilgiler config.py dosyasında saklı ve GitHub'da paylaşılmaması için gitignore dosyasına ekledim.

2. Hava Durumu API’si İçin Kayıt Olma

Hava durumu verilerini almak için ben bu WeatherAPI siteden bir API anahtarı aldım. Fakat bir çok free site mevcut. Kayıt olup API anahtarınızı aldıktan sonra, bu anahtarı da güvenli bir yerde saklayın.

3. Gerekli Python Kütüphanelerini Yükleme

Botumuzu oluşturmak için tweepy, requests ve schedule kütüphanelerini kullanacağız. Bu kütüphaneleri yüklemek için terminal veya komut istemcisinde şu komutları çalıştırın:

4. Botu Oluşturma ve Çalıştırma

  1. Kütüphaneleri kodumuza dahil etmek: Öncelikle tweepy, request ve schedule gibi Python kütüphaneleri kodumuza dahil ediyoruz.
  • import tweepy: Bu kütüphane Twitter API'sini kullanmak için hazır fonksiyonlar kullanmamıza olanak verir. İşimizi kolaylaştırıyor ama kullanmak zorunlu değil kendimiz de tweepy’nin sağladığı fonsiyonları yazabiliriz.
  • import requests: Bu kütüphane HTTP istekleri göndermek ve almak için kullanılır, dış API'lerle etkileşim sağlamak için gereklidir.
  • import schedule: Bu kütüphane belirli görevleri zamanlamak ve düzenlemek için kullanılır, örneğin otomatik işlemleri planlamak için gereklidir. Ben şu an koduma eklemedim. Bir sonraki yazımda kısa bir kod bloğu ile nasıl otomatik paylaşım yapabileceğimizi ayrı bir blog yazısı olarak paylaşacağım.
  • from config import *: config.py dosyasından tüm değişkenler kodumuza dahil ediliyor. Bu dosyada API anahtarları gibi saklanması gerken bilgileri girdim.

2. Twitter API Erişimini Ayarlama: Twitter hesabına erişim sağlaması ve belirli işlemleri yapabilmesi için gereklidir.

Ben bu adımı oluştururken biraz zaman kaybettim. Farklı kaynaklarda eski bilgilerle karşılaştım. Her zaman en güvenilir kaynak kütüphanenin kendi dökümanıdır. Bu tweepy kütüphanesi linkinden isteklerimizi yapmak için kullandığımız Client class ındaki diğer methodlara ulaşabilirsiniz. Ben tweet post etmek için Client class ındaki my_client instance ını oluşturdum ve Twitter API'sine erişmek için Twitter Dev den aldığım gereken kimlik doğrulama bilgilerini ( bearer_token, consumer_key, consumer_secret, access_token, access_token_secret) içine yazdım.

3. config.py : API anahtarlarımız bu dosyada saklı.

4.Fonksiyonlar: Her bir adım için ayrı bir fonksiyon yazdım. Bu şekilde daha anlaşılır ve temiz bir kullanım hedefledim. Fonkisyonları yazarken her birinin anlamlı bir return dönmesine dikkat ettim.

  • get_weather Fonksiyonu: Belirtilen şehir için hava durumu verileri API lerini almak amacıyla WeatherAPI ye HTTP isteği gönderir.
  • create_weather_info_text Fonkisyonu: Dönen json dosyasından istediğimiz verileri kullanarak tweet metnini oluşturur.
  • tweet_post Fonksiyonu: Oluşturulan tweet metnini Twitter’da paylaşır.

Bu adımları takip ederek, basit bir hava durumu botu oluşturabilirsiniz. Projeniz ile hem Python programlama becerilerinizi geliştirebilir hem de Twitter API’sini kullanarak gerçek dünya verileriyle etkileşimkurabilirsiniz. Bir sonraki yazımda, bu botu daha da geliştirmek için otomatik paylaşımları zamanlamayı ve yapay zeka entegrasyonunu nasıl ekleyebileceğinizi anlatacağım.

Eğer aklınıza takılan veya eklemek istediğiniz bir şey varsa, çekinmeden bana yazabilirsiniz!

Kaynaklar: Tweepy DocumentationWebsite, X Developer Platform

--

--