From 2bb3bd6f99d87955f1984a59cc9d37d766f55691 Mon Sep 17 00:00:00 2001 From: SAY-5 Date: Mon, 11 May 2026 15:04:06 -0700 Subject: [PATCH] fix: set User-Agent for Wikipedia OpenSearch requests Closes #159 The Wikimedia User-Agent Policy blocks the default urllib User-Agent ("Python-urllib/x.y"), causing the /wiki command to crash. Set an explicit descriptive User-Agent identifying the bot and linking to the repository, as required by Wikimedia. --- bot/extensions/wikipedia_cog.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/bot/extensions/wikipedia_cog.py b/bot/extensions/wikipedia_cog.py index 65036c92..bd52cbab 100644 --- a/bot/extensions/wikipedia_cog.py +++ b/bot/extensions/wikipedia_cog.py @@ -1,12 +1,17 @@ from json import loads from typing import Any, List from urllib.parse import quote_plus -from urllib.request import urlopen +from urllib.request import Request, urlopen from discord import Button, ButtonStyle, Embed, Interaction, ui from discord.ext.commands import Cog, Context, hybrid_command from discord.ui import View +# Wikimedia requires a descriptive User-Agent identifying the application +# and a way to contact the operator. See: +# https://foundation.wikimedia.org/wiki/Policy:Wikimedia_Foundation_User-Agent_Policy +USER_AGENT = "grace-bot/1.0 (https://github.com/Code-Society-Lab/grace)" + def search_results(search: str) -> List[Any]: """Return search results from Wikipedia for the given search query. @@ -20,7 +25,8 @@ def search_results(search: str) -> List[Any]: url_encode: str = quote_plus(search) base_url: str = f"https://en.wikipedia.org/w/api.php?action=opensearch&format=json&limit=3&namespace=0&search={url_encode}" - with urlopen(base_url) as url: + request = Request(base_url, headers={"User-Agent": USER_AGENT}) + with urlopen(request) as url: return loads(url.read())