Hey there! I have a problem with CRC in account activity api for twitter api premium version 1.1 i basically copy the CRC code (Securing webhooks | Docs | Twitter Developer Platform) modules i use: hmac, hashlib, base64. I also use flask for the webapp and also replit’s IDE for the coding process.
My Code:


@app.route('/webhook/twitter', methods=['GET'])
def webhook_challenge():
    sha256_hash_digest = hmac.new(os.environ["api_key_secret"], msg=request.args.get('crc_token'), digestmod=hashlib.sha256).digest()

    response = {
    'response_token': 'sha256=' + base64.b64encode(sha256_hash_digest)
    }

    return json.dumps(response)

The Error:

* Serving Flask app 'app' (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on all addresses.
   WARNING: This is a development server. Do not use it in a production deployment.
 * Running on http://172.18.0.25:8080/ (Press CTRL+C to quit)
[2021-12-05 09:42:18,995] ERROR in app: Exception on /webhook/twitter [GET]
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/flask/app.py", line 2070, in wsgi_app
    response = self.full_dispatch_request()
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/flask/app.py", line 1515, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/flask/app.py", line 1513, in full_dispatch_request
    rv = self.dispatch_request()
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/flask/app.py", line 1499, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
  File "main.py", line 33, in webhook_challenge
    sha256_hash_digest = hmac.new(os.environ["api_key_secret"], msg=request.args.get('crc_token'), digestmod=hashlib.sha256).digest()
  File "/usr/lib/python3.8/hmac.py", line 153, in new
    return HMAC(key, msg, digestmod)
  File "/usr/lib/python3.8/hmac.py", line 48, in __init__
    raise TypeError("key: expected bytes or bytearray, but got %r" % type(key).__name__)
TypeError: key: expected bytes or bytearray, but got 'str'

Note: twitter actually make the get request, flask log it and send it in my terminal, the problem is in the hmac. Because of this the api returns with this: Non-200 response code during CRC GET request (i.e. 404, 500, etc)

File “/usr/lib/python3.8/hmac.py”, line 48, in init
raise TypeError(“key: expected bytes or bytearray, but got %r” % type(key).name)
TypeError: key: expected bytes or bytearray, but got ‘str’

I think hmac.new takes bytes objects not strings, like this: convert String to Bytes object for hmac.new() in python 3 - Stack Overflow

Ahh yes my bad, my question is something like, which argument require bytes. Anyway thanks for the help Igor! Always come to help people :grin:

Alright. I have another error saying my webhook url doesn’t match the requirements.

raceback (most recent call last):
  File "main.py", line 58, in <module>
    res = client.register_webhook("https://PyTweet.thekungfuchuck.repl.co/webhook/twitter", "Development")
  File "/home/runner/PyTweet/pytweet/client.py", line 574, in register_webhook
    res = self.http.request(
  File "/home/runner/PyTweet/pytweet/http.py", line 190, in request
    check_error(response)
  File "/home/runner/PyTweet/pytweet/http.py", line 71, in check_error
    raise BadRequests(response)
pytweet.errors.BadRequests: Request returned an Exception (status code: 400): Webhook URL does not meet the requirements. Invalid CRC token or json response format.

My code:

@app.route('/webhook/twitter', methods=['GET'])
def webhook_challenge():
    key = os.environ["api_key_secret"].encode("utf-8")
    msg = request.args.get('crc_token').encode("utf-8")
    key = base64.b64encode(key)
    sha256_hash_digest = hmac.new(
        key, 
        msg=msg, 
        digestmod=hashlib.sha256
    ).digest()

    response = {
        'response_token': 'sha256=' + base64.b64encode(sha256_hash_digest).decode("utf-8")
    }

    return json.dumps(response)

Its probably invalid, but i tried the old way doing it (where it was explained in the docs) but it doesnt work probably because th packages are outdated, so do you know how am i able to make CRC challenge?

Does GitHub - RickRedSix/twitter-webhook-boilerplate-python: Starter app / scripts for consuming events via Twitter Account Activity API (beta). or GitHub - twitivity/twitivity: Twitter Accounts Activity API Client Library for Python work for you?

Will try thank you!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.