Following on from an earlier post on the GitHub API, I had the requirement to add web hooks to a group of repos so that all pull requests raised, completed or closed would be posted to the web hook. All the repos have a common prefix and the PyGithub library provides a doc on how to create a web hook so just need to put the two together.
As I want this to be re-runnable, I first need to check there is not already a web hook. For this I created the function has_webhook which iterates through the existing hooks, using the get_hooks function, looking to see if any reference the passed in URL.
With that done I just need to add a little bit of additional code to my githubrepos.py template. First an option to the parameters so I can specify the web hook. Next I need a hook config dictionary for creating any new hooks and a list of events. As this is the same for each, I’ll do this at the start and for the sake of simplicity hardcode the list . Finally for my repo loop I need to call has_webhook function and for any which do not already have the web hook, create it using the create_hook function.
This gives me the final webhooks.py.
As a final note. If you are looking to integration Github into Slack or MS Teams, both offer apps which largely automate the process. Ultimately what they are doing is setting up a webhook in the same way as above.