text: import requests
  import os
  import json
  
  
  bearer_token = os.environ.get("BEARER_TOKEN")
  
  def bearer_oauth(r):
      """
      Method required by bearer token authentication.
      """
  
      r.headers["Authorization"] = f"Bearer {bearer_token}"
      r.headers["User-Agent"] = "S-n-Tweet Alpha"
      return r
  
  
  def get_rules():
      response = requests.get(
          "https://api.twitter.com/2/tweets/search/stream/rules", auth=bearer_oauth
      )
      if response.status_code != 200:
          raise Exception(
              "Cannot get rules (HTTP {}): {}".format(response.status_code, response.text)
          )
      print(json.dumps(response.json(), indent=4, sort_keys=True))
      return response.json()
  
  
  def delete_all_rules(rules):
      if rules is None or "data" not in rules:
          return None
  
      ids = list(map(lambda rule: rule["id"], rules["data"]))
      payload = {"delete": {"ids": ids}}
      response = requests.post(
          "https://api.twitter.com/2/tweets/search/stream/rules",
          auth=bearer_oauth,
          json=payload
      )
      if response.status_code != 200:
          raise Exception(
              "Cannot delete rules (HTTP {}): {}".format(
                  response.status_code, response.text
              )
          )
      print(json.dumps(response.json()))
  
  
  def set_rules(delete):
      # You can adjust the rules if needed
      rules = [
          {"value": "TSLA"},
          {"value": "MSFT"}, 
          {"value": "GOOG"}, 
      ]
      payload = {"add": rules}
      response = requests.post(
          "https://api.twitter.com/2/tweets/search/stream/rules",
          auth=bearer_oauth,
          json=payload,
      )
      if response.status_code != 201:
          raise Exception(
              "Cannot add rules (HTTP {}): {}".format(response.status_code, response.text)
          )
      print(json.dumps(response.json(), indent=4, sort_keys=True))
  
  
  def get_stream(set):
      response = requests.get(
          "https://api.twitter.com/2/tweets/search/stream", auth=bearer_oauth, stream=True,
      )
      print(response.status_code)
      if response.status_code != 200:
          raise Exception(
              "Cannot get stream (HTTP {}): {}".format(
                  response.status_code, response.text
              )
          )
      for response_line in response.iter_lines():
          if response_line:
              json_response = json.loads(response_line)
              print(json.dumps(json_response, indent=4, sort_keys=True))
  
  
  def main():
      rules = get_rules()
      delete = delete_all_rules(rules)
      set = set_rules(delete)
      get_stream(set)
      #get_stream(rules)
  
  
  if __name__ == "__main__":
      main()