Skip to content

Lemmy

Implements the Lemmy class.

Lemmy(lemmy_url, username, password, user_agent, request_timeout=30)

The Lemmy class provides the main entrypoint for pylemmy, and Lemmy's API.

This class manages all the settings relating how to access your chosen Lemmy instance, and implements the Lemmy API.

Example:

from pylemmy import Lemmy

lemmy = Lemmy(
    lemmy_url="http://127.0.0.1:8536",
    username="lemmy",
    password="lemmylemmy",
    user_agent="custom user-agent (by u/USERNAME)",
)

Initialize a Lemmy instance.

Parameters:

  • lemmy_url (Union[str, AnyUrl]) –

    The URL for the Lemmy instance you want to access.

  • username (Optional[str]) –

    Your Lemmy username or email.

  • password (Optional[str]) –

    Your Lemmy password

  • user_agent (str) –

    The user agent the requests will use.

  • request_timeout (int, default: 30 ) –

    A maximum timeout to wait for requests (in seconds).

Source code in pylemmy/lemmy.py
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
def __init__(
    self,
    lemmy_url: Union[str, AnyUrl],
    username: Optional[str],
    password: Optional[str],
    user_agent: str,
    request_timeout: int = 30,
):
    """Initialize a Lemmy instance.

    :param lemmy_url: The URL for the Lemmy instance you want to access.
    :param username: Your Lemmy username or email.
    :param password: Your Lemmy password
    :param user_agent: The user agent the requests will use.
    :param request_timeout: A maximum timeout to wait for requests (in seconds).
    """
    self.lemmy_url = (
        lemmy_url
        if isinstance(lemmy_url, AnyUrl)
        else TypeAdapter(AnyUrl).validate_python(lemmy_url)
    )
    self.username = username
    self.password = password
    self.user_agent = user_agent

    self.request_timeout = request_timeout

    self._login_response: Optional[api.auth.LoginResponse] = None

    self.session = requests.Session()
    self.session.headers.update({"User-Agent": self.user_agent})

create_community(name, title, **kwargs)

Create a community with the given name and title.

Parameters:

  • name (str) –

    Name of the community (stub-like, this will be in the URL).

  • title (str) –

    Title of the community, in natural language.

  • kwargs –

    See optional arguments in CreateCommunity.

Source code in pylemmy/lemmy.py
128
129
130
131
132
133
134
135
136
137
138
139
140
141
def create_community(self, name: str, title: str, **kwargs) -> Community:
    """Create a community with the given name and title.

    :param name: Name of the community (stub-like, this will be in the URL).
    :param title: Title of the community, in natural language.
    :param kwargs: See optional arguments in [CreateCommunity](
    https://join-lemmy.org/api/interfaces/CreateCommunity.html).
    """
    self.get_token()
    payload = api.community.CreateCommunity(name=name, title=title, **kwargs)
    result = self.post_request(LemmyAPI.Community, params=payload)
    parsed_result = api.community.CommunityResponse(**result)

    return Community(self, parsed_result.community_view)

get_comment(comment_id=None)

Get a comment from its id.

Parameters:

  • comment_id (Optional[int], default: None ) –

    Id of the comment.

Source code in pylemmy/lemmy.py
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
def get_comment(self, comment_id: Optional[int] = None) -> Comment:
    """Get a comment from its id.

    :param comment_id: Id of the comment.
    """
    if comment_id is not None:
        payload = api.comment.GetComment(id=comment_id)
    else:
        msg = "Need to give a comment id."
        raise ValueError(msg)

    result = self.get_request(LemmyAPI.Comment, params=payload)
    parsed_result = api.comment.CommentResponse(**result)

    return Comment(self, parsed_result.comment_view)

get_community(community)

Get a community by id or name.

Parameters:

  • community (Union[str, int]) –

    Either a community id (int) or name (str).

Source code in pylemmy/lemmy.py
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
def get_community(self, community: Union[str, int]) -> Community:
    """Get a community by id or name.

    :param community: Either a community id (int) or name (str).
    """
    if isinstance(community, str):
        payload = api.community.GetCommunity(name=community)
    elif isinstance(community, int):
        payload = api.community.GetCommunity(id=community)
    else:
        raise ValueError()

    result = self.get_request(LemmyAPI.Community, params=payload)
    parsed_result = api.community.GetCommunityResponse(**result)
    return Community(self, parsed_result.community_view)

get_person_details(person_id=None, username=None)

Get a user from its id or username.

Parameters:

  • person_id –

    Id of the user.

  • username –

    the username of the user

Source code in pylemmy/lemmy.py
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
def get_person_details(self, person_id=None, username=None) -> Person:
    """Get a user from its id or username.

    :param person_id: Id of the user.
    :param username: the username of the user
    """
    if person_id is not None:
        payload = api.person.GetPersonDetails(person_id=person_id)
    elif username is not None:
        payload = api.person.GetPersonDetails(username=username)
    else:
        msg = "Need to give a person_id or username."
        raise ValueError(msg)

    result = self.get_request(LemmyAPI.Person, params=payload)
    parsed_result = api.person.GetPersonDetailsResponse(**result)

    return Person(
        self, parsed_result.person_view.counts, parsed_result.person_view.person
    )

get_post(*, post_id=None, comment_id=None)

Get a post from its id.

Parameters:

  • post_id (Optional[int], default: None ) –

    Id of the post.

  • comment_id (Optional[int], default: None ) –

    Id of the comment.

Source code in pylemmy/lemmy.py
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
def get_post(
    self, *, post_id: Optional[int] = None, comment_id: Optional[int] = None
) -> Post:
    """Get a post from its id.

    :param post_id: Id of the post.
    :param comment_id: Id of the comment.
    """
    if post_id is not None:
        payload = api.post.GetPost(id=post_id)
    elif comment_id is not None:
        payload = api.post.GetPost(comment_id=comment_id)
    else:
        msg = "Need to give either a post id or a comment id."
        raise ValueError(msg)

    result = self.get_request(LemmyAPI.Post, params=payload)
    parsed_result = api.post.GetPostResponse(**result)

    return Post(self, parsed_result.post_view)

get_request(path, params=None)

Send a GET request to the desired path.

Parameters:

  • path (LemmyAPI) –

    A Lemmy endpoint.

  • params (Optional[BaseApiModel], default: None ) –

    Parameters to send with the request (in the URL).

Source code in pylemmy/lemmy.py
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
def get_request(
    self,
    path: LemmyAPI,
    params: Optional[BaseApiModel] = None,
):
    """Send a GET request to the desired path.

    :param path: A Lemmy endpoint.
    :param params: Parameters to send with the request (in the URL).
    """
    token = self.get_token_optional()
    response = self.session.get(
        self._get_url(path),
        params=params.dict() if params is not None else {},
        headers={"Authorization": f"Bearer {token}" if token else None},
        timeout=self.request_timeout,
    )
    response.raise_for_status()
    return response.json()

get_token()

Get the jwt session token.

Source code in pylemmy/lemmy.py
 95
 96
 97
 98
 99
100
101
def get_token(self) -> str:
    """Get the jwt session token."""
    jwt = self.login().jwt
    if jwt is None:
        msg = "No jwt token was found, try logging in again."
        raise RuntimeError(msg)
    return jwt

get_token_optional()

Get the jwt session token if it exists, or None.

This should be used for requests that don't need authentication.

Source code in pylemmy/lemmy.py
103
104
105
106
107
108
109
110
def get_token_optional(self) -> Optional[str]:
    """Get the jwt session token if it exists, or `None`.

    This should be used for requests that don't need authentication.
    """
    if self.username is None or self.password is None:
        return None
    return self.get_token()

list_comment_reports(**kwargs)

List comment reports.

Parameters:

Source code in pylemmy/lemmy.py
226
227
228
229
230
231
232
233
234
235
236
237
def list_comment_reports(self, **kwargs) -> List[api.comment.CommentReportView]:
    """List comment reports.

    :param kwargs: See optional arguments in [ListCommentReports](
    https://join-lemmy.org/api/interfaces/ListCommentReports.html).
    """
    self.get_token()
    payload = api.comment.ListCommentReports(**kwargs)
    result = self.get_request(LemmyAPI.ListPostReports, params=payload)
    parsed_result = api.comment.ListCommentReportsResponse(**result)

    return parsed_result.comment_reports

list_communities(**kwargs)

List the communities in the current Lemmy instance.

Parameters:

Source code in pylemmy/lemmy.py
143
144
145
146
147
148
149
150
151
152
153
def list_communities(self, **kwargs) -> List[Community]:
    """List the communities in the current Lemmy instance.

    :param kwargs: See optional arguments in [ListCommunities](
    https://join-lemmy.org/api/interfaces/ListCommunities.html).
    """
    payload = api.community.ListCommunities(**kwargs)
    result = self.get_request(LemmyAPI.ListCommunities, params=payload)
    parsed_result = api.community.ListCommunitiesResponse(**result)

    return [Community(self, view) for view in parsed_result.communities]

list_post_reports(**kwargs)

List post reports.

Parameters:

Source code in pylemmy/lemmy.py
213
214
215
216
217
218
219
220
221
222
223
224
def list_post_reports(self, **kwargs) -> List[api.post.PostReportView]:
    """List post reports.

    :param kwargs: See optional arguments in [ListPostReports](
    https://join-lemmy.org/api/interfaces/ListPostReports.html).
    """
    self.get_token()
    payload = api.post.ListPostReports(**kwargs)
    result = self.get_request(LemmyAPI.ListPostReports, params=payload)
    parsed_result = api.post.ListPostReportsResponse(**result)

    return parsed_result.post_reports

login()

Login to Lemmy.

If the user is already logged in, return the response to the original login request, with the session information.

Source code in pylemmy/lemmy.py
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
def login(self) -> api.auth.LoginResponse:
    """Login to Lemmy.

    If the user is already logged in, return the response to the original login
    request, with the session information.
    """
    if self._login_response is None:
        if self.username is not None and self.password is not None:
            response = self.post_request(
                LemmyAPI.Login,
                params=api.auth.Login(
                    username_or_email=self.username, password=self.password
                ),
            )
            parsed_response = api.auth.LoginResponse(**response)
            if parsed_response.jwt is None:
                msg = "Couldn't login! Have you verified your email?"
                raise RuntimeError(msg)
            self._login_response = parsed_response
        else:
            msg = "Need to provide username and password!"
            raise ValueError(msg)
    return self._login_response

multi_communities_stream(communities)

Get streams for multiple communities.

Example: A simple example where we want to print the content of each post/comment.

def process_content(elem: Union[Post, Comment]):
    if isinstance(Post, elem):
        print(elem.post_view.post.name)
    elif isinstance(Comment, elem):
        print(elem.comment_view.comment.content

multi_stream = lemmy.multi_communities_stream(["community1", "community2"])
multi_stream.content_apply(process_content)

Parameters:

  • communities (Iterable[Union[int, str, Community]]) –

    An iterable of community ids, names or instances of [Community][pylemmy.community.Community].

Source code in pylemmy/lemmy.py
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
def multi_communities_stream(
    self, communities: Iterable[Union[int, str, Community]]
) -> MultiCommunityStream:
    """Get streams for multiple communities.

    Example:
    A simple example where we want to print the content of each post/comment.

        def process_content(elem: Union[Post, Comment]):
            if isinstance(Post, elem):
                print(elem.post_view.post.name)
            elif isinstance(Comment, elem):
                print(elem.comment_view.comment.content

        multi_stream = lemmy.multi_communities_stream(["community1", "community2"])
        multi_stream.content_apply(process_content)

    :param communities: An iterable of community ids, names or instances of
    [Community][pylemmy.community.Community].
    """
    communities_list = (
        x if isinstance(x, Community) else self.get_community(x)
        for x in communities
    )
    return MultiCommunityStream(list(communities_list))

post_request(path, params=None)

Send a POST request to the desired path.

Parameters:

  • path (LemmyAPI) –

    A Lemmy endpoint.

  • params (Optional[BaseApiModel], default: None ) –

    Parameters to send with the request (in the body).

Source code in pylemmy/lemmy.py
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def post_request(
    self,
    path: LemmyAPI,
    params: Optional[BaseApiModel] = None,
):
    """Send a POST request to the desired path.

    :param path: A Lemmy endpoint.
    :param params: Parameters to send with the request (in the body).
    """
    token = None if path is LemmyAPI.Login else self.get_token_optional()
    response = self.session.post(
        self._get_url(path),
        json=params.dict() if params is not None else {},
        headers={"Authorization": f"Bearer {token}" if token else None},
        timeout=self.request_timeout,
    )
    response.raise_for_status()
    return response.json()

put_request(path, params=None)

Send a PUT request to the desired path.

Parameters:

  • path (LemmyAPI) –

    A Lemmy endpoint.

  • params (Optional[BaseApiModel], default: None ) –

    Parameters to send with the request (in the URL).

Source code in pylemmy/lemmy.py
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
def put_request(
    self,
    path: LemmyAPI,
    params: Optional[BaseApiModel] = None,
):
    """Send a PUT request to the desired path.

    :param path: A Lemmy endpoint.
    :param params: Parameters to send with the request (in the URL).
    """
    token = self.get_token_optional()
    response = self.session.put(
        self._get_url(path),
        params=params.dict() if params is not None else {},
        headers={"Authorization": f"Bearer {token}" if token else None},
        timeout=self.request_timeout,
    )
    return response.json()