-
Notifications
You must be signed in to change notification settings - Fork 1
Wikipedia command port from grace to ada #15
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
a583113
Port Wikipedia search command from Grace
Shadwz17 f419722
Guard against malformed API responses
Shadwz17 51b6791
Fix minor PEP 8 issues
Shadwz17 8a8f354
Address Wikipedia extension review feedback
Shadwz17 9e26fc0
Add network error tests
Shadwz17 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| import asyncio | ||
| import requests | ||
| from matrix import Extension, Context | ||
|
|
||
| type WikiPayload = tuple[str, list[str], list[str], list[str]] | ||
|
|
||
| _RESULT_LIMIT = 3 | ||
| _REQUEST_TIMEOUT = 5 | ||
| _USER_AGENT = "AdaBot/1.0 (https://github.com/Code-Society-Lab/ada)" | ||
| _API_URL = "https://en.wikipedia.org/w/api.php" | ||
|
|
||
|
|
||
| extension = Extension("wikipedia") | ||
|
|
||
|
|
||
| @extension.command( | ||
| usage="wiki <search query>", | ||
| description="Search Wikipedia and display the top results.", | ||
| ) | ||
| async def wiki(ctx: Context, *args: str) -> None: | ||
| if not args: | ||
| raise ValueError("Please provide a search query. Usage: !wiki <search query>") | ||
|
|
||
| query = " ".join(args).strip() | ||
| if len(query) > 300: | ||
| raise ValueError( | ||
| "Search query is too long. Please limit it to 300 characters or less." | ||
| ) | ||
| payload = await asyncio.to_thread(_search_wikipedia, query) | ||
| result_message = _format_results(query, payload) | ||
| await ctx.reply(result_message) | ||
|
|
||
|
|
||
| @wiki.error(exception=requests.RequestException) | ||
| async def wiki_unreachable(ctx: Context, error: requests.RequestException) -> None: | ||
| await ctx.reply("Sorry, something went wrong while contacting Wikipedia") | ||
|
|
||
|
|
||
| @wiki.error(exception=ValueError) | ||
| async def wiki_invalid(ctx: Context, error: ValueError) -> None: | ||
| await ctx.reply(str(error)) | ||
|
|
||
|
|
||
| def _search_wikipedia(query: str) -> WikiPayload: | ||
| params: dict[str, str | int] = { | ||
| "action": "opensearch", | ||
| "format": "json", | ||
| "namespace": 0, | ||
| "limit": _RESULT_LIMIT, | ||
| "search": query, | ||
| } | ||
| response = requests.get( | ||
| _API_URL, | ||
| params=params, | ||
| headers={"User-Agent": _USER_AGENT}, | ||
| timeout=_REQUEST_TIMEOUT, | ||
| ) | ||
| response.raise_for_status() | ||
| return response.json() | ||
|
|
||
|
|
||
| def _format_results(query: str, payload: WikiPayload) -> str: | ||
| if ( | ||
| not isinstance(payload, (list, tuple)) | ||
| or len(payload) < 4 | ||
| or not isinstance(payload[1], list) | ||
| or not isinstance(payload[3], list) | ||
| ): | ||
| raise ValueError("Unexpected response format from Wikipedia API.") | ||
|
|
||
| titles, urls = payload[1], payload[3] | ||
| if not titles: | ||
| raise ValueError(f"No results found for '{query}'.") | ||
|
|
||
| result_lines = [ | ||
| f"> **{i}.** [{title}](<{url}>)" | ||
| for i, (title, url) in enumerate(zip(titles, urls), start=1) | ||
| ] | ||
| header = f'#### Wikipedia results for "_{query}_"' | ||
| return f"{header}\n\n" + "\n".join(result_lines) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,91 @@ | ||
| import pytest | ||
| import requests | ||
| from unittest.mock import patch, MagicMock | ||
|
|
||
| from bot.extensions.wikipedia_extension import ( | ||
| _format_results, | ||
| _search_wikipedia, | ||
| ) | ||
|
|
||
|
|
||
| def test_format_results_renders_header_and_lines() -> None: | ||
| payload = ("py", ["Python"], [""], ["https://en.wikipedia.org/wiki/Python"]) | ||
| result = _format_results("py", payload) | ||
|
|
||
| assert '#### Wikipedia results for "_py_"' in result | ||
| assert "> **1.** [Python](<https://en.wikipedia.org/wiki/Python>)" in result | ||
|
|
||
|
|
||
| def test_format_results_raises_on_non_list_payload() -> None: | ||
| with pytest.raises(ValueError, match="Unexpected response format"): | ||
| _format_results("q", {}) # type: ignore[arg-type] | ||
|
|
||
|
|
||
| def test_format_results_raises_on_short_payload() -> None: | ||
| with pytest.raises(ValueError, match="Unexpected response format"): | ||
| _format_results("q", []) # type: ignore[arg-type] | ||
|
|
||
|
|
||
| def test_format_results_raises_on_wrong_inner_types() -> None: | ||
| with pytest.raises(ValueError, match="Unexpected response format"): | ||
| _format_results("q", ["query", 2, [""], ["https://test.link"]]) # type: ignore[arg-type] | ||
|
|
||
|
|
||
| def test_format_results_raises_on_no_results() -> None: | ||
| with pytest.raises(ValueError, match="No results found"): | ||
| _format_results("q", ("query", [], [""], ["https://test.link"])) | ||
|
|
||
|
|
||
| def test_search_wikipedia_calls_api_with_correct_params() -> None: | ||
| fake_payload = ["query", ["Title"], [""], ["https://test.link"]] | ||
|
|
||
| fake_response = MagicMock() | ||
| fake_response.json.return_value = fake_payload | ||
|
|
||
| with patch( | ||
| "bot.extensions.wikipedia_extension.requests.get", return_value=fake_response | ||
| ) as mock_get: | ||
|
|
||
| result = _search_wikipedia("test query") | ||
|
|
||
| mock_get.assert_called_once_with( | ||
| "https://en.wikipedia.org/w/api.php", | ||
| params={ | ||
| "action": "opensearch", | ||
| "format": "json", | ||
| "namespace": 0, | ||
| "limit": 3, | ||
| "search": "test query", | ||
| }, | ||
| headers={ | ||
| "User-Agent": "AdaBot/1.0 (https://github.com/Code-Society-Lab/ada)" | ||
| }, | ||
| timeout=5, | ||
| ) | ||
| assert result == fake_payload | ||
|
|
||
|
|
||
| def test_search_wikipedia_raises_on_http_error() -> None: | ||
| fake_response = MagicMock() | ||
| fake_response.raise_for_status.side_effect = requests.HTTPError("error") | ||
|
|
||
| with patch( | ||
| "bot.extensions.wikipedia_extension.requests.get", return_value=fake_response | ||
| ): | ||
| with pytest.raises(requests.HTTPError, match="error"): | ||
| _search_wikipedia("python") | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "exception", | ||
| [ | ||
| requests.ConnectionError("connection failed"), | ||
| requests.Timeout("request timed out"), | ||
| ], | ||
| ) | ||
| def test_search_wikipedia_raises_on_network_error(exception) -> None: | ||
| with patch( | ||
| "bot.extensions.wikipedia_extension.requests.get", side_effect=exception | ||
| ): | ||
| with pytest.raises(type(exception), match=str(exception)): | ||
| _search_wikipedia("python") |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.