Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
bots: Add a setting to customize the Welcome Bot message.
Saubhagya Patelbb5c87e306d3
diff --git a/api_docs/changelog.md b/api_docs/changelog.mdindex 26c1c233409..08204d28950 100644--- a/api_docs/changelog.md+++ b/api_docs/changelog.md@@ -20,6 +20,22 @@ format used by the Zulip server that they are interacting with.## Changes in Zulip 11.0+**Feature level 416**++* [`POST /invites`](/api/send-invites), [`POST+ /invites/multiuse`](/api/create-invite-link): Added a new parameter+ `welcome_message_custom_text` which allows the users to add a+ Welcome Bot custom message for new users through invitations.++* [`POST /register`](/api/register-queue), [`POST /events`](/api/get-events),+ `PATCH /realm`: Added `welcome_message_custom_text` realm setting which is the+ default custom message for the Welcome Bot when sending invitations to new users.++* [`POST /realm/test_welcome_bot_custom_message`](/api/test-welcome-bot-custom-message):+ Added new endpoint test messages with the Welcome Bot custom message. The test+ messages are sent to the acting administrator, allowing them to preview how the+ custom welcome message will appear to new users upon joining the organization.+**Feature level 415*** [`POST /reminders`](/api/create-message-reminder): Added parameterdiff --git a/api_docs/include/rest-endpoints.md b/api_docs/include/rest-endpoints.mdindex f76284b1f2c..78eb704a707 100644--- a/api_docs/include/rest-endpoints.md+++ b/api_docs/include/rest-endpoints.md@@ -144,6 +144,7 @@* [Get all data exports](/api/get-realm-exports)* [Create a data export](/api/export-realm)* [Get data export consent state](/api/get-realm-export-consents)+* [Test welcome bot custom message](/api/test-welcome-bot-custom-message)#### Real-time eventsdiff --git a/tools/lib/capitalization.py b/tools/lib/capitalization.pyindex e32505df5db..950765b00b6 100644--- a/tools/lib/capitalization.py+++ b/tools/lib/capitalization.py@@ -160,6 +160,8 @@ IGNORED_PHRASES = [r"to add a new line",# Used in showing Notification Bot read receipts message"Notification Bot",+ # Used in strings around welcome bot custom messages+ r"Welcome Bot",# Used in presence_enabled setting labelr"invisible mode off",# Typeahead suggestions for "Pronouns" custom field type.diff --git a/version.py b/version.pyindex b4d3dfcf129..80405dfe9db 100644--- a/version.py+++ b/version.py@@ -34,7 +34,7 @@ DESKTOP_WARNING_VERSION = "5.9.3"# new level means in api_docs/changelog.md, as well as "**Changes**"# entries in the endpoint's documentation in `zulip.yaml`.-API_FEATURE_LEVEL = 415+API_FEATURE_LEVEL = 416# Bump the minor PROVISION_VERSION to indicate that folks should provision# only when going from an old version of the code to a newer version. Bumpdiff --git a/web/src/admin.ts b/web/src/admin.tsindex 6c42793403b..dd4a53a7166 100644--- a/web/src/admin.ts+++ b/web/src/admin.ts@@ -54,6 +54,9 @@ const admin_settings_label = {defaultMessage: "Send weekly digest emails to inactive users",}),realm_default_code_block_language: $t({defaultMessage: "Default language for code blocks"}),+ realm_enable_welcome_message_custom_text: $t({+ defaultMessage: "Add a custom Welcome Bot message for new users",+ }),// Organization permissionsrealm_require_unique_names: $t({defaultMessage: "Require unique names"}),@@ -199,6 +202,9 @@ export function build_page(): void {realm_topics_policy_values: settings_config.get_realm_topics_policy_values(),empty_string_topic_display_name: util.get_final_topic_display_name(""),realm_send_welcome_emails: realm.realm_send_welcome_emails,+ realm_enable_welcome_message_custom_text:+ realm.realm_welcome_message_custom_text.length > 0,+ realm_welcome_message_custom_text: realm.realm_welcome_message_custom_text,realm_require_e2ee_push_notifications: realm.realm_require_e2ee_push_notifications,realm_message_content_allowed_in_email_notifications:realm.realm_message_content_allowed_in_email_notifications,diff --git a/web/src/invite.ts b/web/src/invite.tsindex ae55e534bac..6a7e20be97c 100644--- a/web/src/invite.ts+++ b/web/src/invite.ts@@ -53,6 +53,7 @@ type CommonInvitationData = {invite_expires_in_minutes: string;invitee_emails: string;include_realm_default_subscriptions: string;+ welcome_message_custom_text?: string;};function reset_error_messages(): void {@@ -117,6 +118,29 @@ function get_common_invitation_data(): CommonInvitationData {data.invitee_emails += "," + current_email;}}++ if (current_user.is_admin) {+ const realm_welcome_message_configured = realm.realm_welcome_message_custom_text.length > 0;+ const send_realm_default_custom_message = $(+ "#send_default_realm_welcome_message_custom_text",+ ).is(":checked");+ const send_custom_message = $("#send_custom_welcome_message_custom_text").is(":checked");+ const welcome_message_custom_text = $<HTMLTextAreaElement>(+ "#invite_welcome_custom_message_text",+ )+ .val()!+ .trim();++ if (+ (realm_welcome_message_configured && !send_realm_default_custom_message) ||+ (!realm_welcome_message_configured &&+ send_custom_message &&+ welcome_message_custom_text.length > 0)+ ) {+ data.welcome_message_custom_text = welcome_message_custom_text;+ }+ }+return data;}@@ -305,6 +329,28 @@ function set_streams_to_join_list_visibility(): void {}}+function set_welcome_message_custom_text_visibility(): void {+ if (!current_user.is_admin) {+ return;+ }++ const realm_welcome_message_configured = realm.realm_welcome_message_custom_text.length > 0;+ const send_realm_default_custom_message = $(+ "#send_default_realm_welcome_message_custom_text",+ ).is(":checked");+ const send_custom_message = $("#send_custom_welcome_message_custom_text").is(":checked");++ const should_show_welcome_message_container =+ (send_custom_message && !realm_welcome_message_configured) ||+ (!send_realm_default_custom_message && realm_welcome_message_configured);++ if (should_show_welcome_message_container) {+ $("#invite_welcome_message_custom_text_container").show();+ } else {+ $("#invite_welcome_message_custom_text_container").hide();+ }+}+async function update_guest_visible_users_count_and_stream_ids(): Promise<void> {const invite_as = Number.parseInt($<HTMLSelectOneElement>("select:not([multiple])#invite_as").val()!,@@ -390,6 +436,7 @@ function open_invite_user_modal(e: JQuery.ClickEvent<Document, undefined>): voidtime_choices: settings_config.custom_time_unit_values,show_select_default_streams_option: stream_data.get_default_stream_ids().length > 0,user_has_email_set: !settings_data.user_email_not_configured(),+ default_welcome_message_custom_text: realm.realm_welcome_message_custom_text,});function invite_user_modal_post_render(): void {@@ -418,6 +465,8 @@ function open_invite_user_modal(e: JQuery.ClickEvent<Document, undefined>): voiduser_group_pill_widget = user_group_picker_pill.create($user_group_pill_container);}+ set_welcome_message_custom_text_visibility();+$("#invite_streams_container .input, #invite_select_default_streams").on("change",() => void update_guest_visible_users_count_and_stream_ids(),@@ -515,6 +564,12 @@ function open_invite_user_modal(e: JQuery.ClickEvent<Document, undefined>): voidset_streams_to_join_list_visibility();});+ $(+ "#send_default_realm_welcome_message_custom_text, #send_custom_welcome_message_custom_text",+ ).on("change", () => {+ set_welcome_message_custom_text_visibility();+ });+if (!user_has_email_set) {$(util.the($<HTMLFormElement>("form#invite-user-form")).elements).prop("disabled",diff --git a/web/src/server_events_dispatch.js b/web/src/server_events_dispatch.jsindex bbb0fadd4f9..2a125b877e2 100644--- a/web/src/server_events_dispatch.js+++ b/web/src/server_events_dispatch.js@@ -324,6 +324,7 @@ export function dispatch_normal_event(event) {giphy_rating: giphy.update_giphy_rating,waiting_period_threshold: noop,want_advertise_in_communities_directory: noop,+ welcome_message_custom_text: noop,enable_read_receipts: settings_account.update_send_read_receipts_tooltip,enable_guest_user_dm_warning: compose_validate.warn_if_guest_in_dm_recipient,enable_guest_user_indicator: noop,diff --git a/web/src/settings_org.ts b/web/src/settings_org.tsindex 12cd802f98a..ae110123c05 100644--- a/web/src/settings_org.ts+++ b/web/src/settings_org.ts@@ -3,6 +3,7 @@ import $ from "jquery";import assert from "minimalistic-assert";import * as z from "zod/mini";+import render_action_button from "../templates/components/action_button.hbs";import render_settings_deactivate_realm_modal from "../templates/confirm_dialog/confirm_deactivate_realm.hbs";import render_settings_admin_auth_methods_list from "../templates/settings/admin_auth_methods_list.hbs";@@ -17,10 +18,12 @@ import {type RealmGroupSettingNameSupportingAnonymousGroups,realm_group_setting_name_supporting_anonymous_groups_schema,} from "./group_permission_settings.ts";+import * as hash_util from "./hash_util.ts";import {$t, $t_html, get_language_name} from "./i18n.ts";import * as information_density from "./information_density.ts";import * as keydown_util from "./keydown_util.ts";import * as loading from "./loading.ts";+import * as message_store from "./message_store.ts";import * as pygments_data from "./pygments_data.ts";import * as realm_icon from "./realm_icon.ts";import * as realm_logo from "./realm_logo.ts";@@ -359,6 +362,73 @@ function disable_create_user_groups_if_on_limited_plan(): void {}}+function set_welcome_message_custom_text_visibility(): void {+ const welcome_message_custom_text_is_configured =+ realm.realm_welcome_message_custom_text.length > 0;+ $("input#id_realm_enable_welcome_message_custom_text").prop(+ "checked",+ welcome_message_custom_text_is_configured,+ );+ settings_components.change_element_block_display_property(+ "id_realm_welcome_message_custom_text",+ welcome_message_custom_text_is_configured,+ );+ if (welcome_message_custom_text_is_configured) {+ const setting_value = realm.realm_welcome_message_custom_text;+ $("#id_realm_welcome_message_custom_text").val(setting_value);+ } else {+ $("#id_realm_welcome_message_custom_text").val("");+ }+ update_test_welcome_bot_custom_message_button_status();+}++function update_view_welcome_bot_custom_message_button_status(+ message_id: number | undefined,+ is_error: boolean,+): void {+ $("#view_welcome_bot_custom_message").remove();+ const args = {+ attention: is_error ? "borderless" : "quiet",+ intent: is_error ? "danger" : "success",+ label: is_error+ ? $t({defaultMessage: "Error sending message"})+ : $t({defaultMessage: "View message"}),+ id: "view_welcome_bot_custom_message",+ };++ const view_message_button_html = render_action_button(args);+ $("#welcome_message_custom_text_buttons_container").append($(view_message_button_html));+ const $view_message_button = $("#view_welcome_bot_custom_message");++ if (is_error) {+ $view_message_button.prop("disabled", true).css("opacity", 1);+ return;+ }++ assert(message_id !== undefined);+ $view_message_button.attr("data-message-id", message_id);+ $view_message_button.on("click", (e) => {+ e.preventDefault();+ const message_id = Number($view_message_button.attr("data-message-id"));+ const message = message_store.get(message_id);+ assert(message !== undefined);+ window.location.href = hash_util.by_conversation_and_time_url(message);+ });+}++function update_test_welcome_bot_custom_message_button_status(): void {+ const $test_message_button = $("#send_test_welcome_bot_custom_message");++ const message_text = $<HTMLTextAreaElement>("#id_realm_welcome_message_custom_text")+ .val()!+ .trim();+ if (message_text !== "") {+ $test_message_button.prop("disabled", false);+ return;+ }+ $test_message_button.prop("disabled", true);+}+export function check_disable_direct_message_initiator_group_widget(): void {const direct_message_permission_group_widget = settings_components.get_group_setting_widget("realm_direct_message_permission_group",@@ -580,6 +650,9 @@ export function discard_realm_property_element_changes(elem: HTMLElement): voidcase "realm_waiting_period_threshold":set_realm_waiting_period_setting();break;+ case "realm_welcome_message_custom_text":+ set_welcome_message_custom_text_visibility();+ break;default:if (property_value !== undefined) {const validated_property_value = z@@ -1223,6 +1296,19 @@ export function register_save_discard_widget_handlers();}+ if ($(this).hasClass("realm_enable_welcome_message_custom_text")) {+ const is_checked = $(this).is(":checked");+ settings_components.change_element_block_display_property(+ "id_realm_welcome_message_custom_text",+ is_checked,+ );+ if (!is_checked) {+ $("#id_realm_welcome_message_custom_text").val("");+ } else {+ $("#id_realm_welcome_message_custom_text").trigger("focus");+ }+ }+const $subsection = $(this).closest(".settings-subsection-parent");if (for_realm_default_settings) {settings_components.save_discard_default_realm_settings_widget_status_handler(@@ -1351,6 +1437,7 @@ export function build_page(): void {set_digest_emails_weekday_visibility();set_create_web_public_stream_dropdown_visibility();disable_create_user_groups_if_on_limited_plan();+ set_welcome_message_custom_text_visibility();register_save_discard_widget_handlers($(".admin-realm-form"), "/json/realm", false);@@ -1469,6 +1556,34 @@ export function build_page(): void {settings_realm_domains.show_realm_domains_modal();});+ $<HTMLTextAreaElement>("#id_realm_welcome_message_custom_text").on("input", () => {+ update_test_welcome_bot_custom_message_button_status();+ });++ $("#send_test_welcome_bot_custom_message").on("click", (e) => {+ e.preventDefault();+ const welcome_message_custom_text = $<HTMLTextAreaElement>(+ "#id_realm_welcome_message_custom_text",+ )+ .val()!+ .trim();+ assert(welcome_message_custom_text !== "");++ channel.post({+ url: "/json/realm/test_welcome_bot_custom_message",+ data: {+ welcome_message_custom_text,+ },+ success(data) {+ const {message_id} = z.object({message_id: z.number()}).parse(data);+ update_view_welcome_bot_custom_message_button_status(message_id, false);+ },+ error() {+ update_view_welcome_bot_custom_message_button_status(undefined, true);+ },+ });+ });+function realm_icon_logo_upload_complete($spinner: JQuery,$upload_text: JQuery,diff --git a/web/src/state_data.ts b/web/src/state_data.tsindex 18d070eb8ea..cf3518b1e9a 100644--- a/web/src/state_data.ts+++ b/web/src/state_data.ts@@ -446,6 +446,7 @@ export const realm_schema = z.object({realm_video_chat_provider: z.number(),realm_waiting_period_threshold: z.number(),realm_want_advertise_in_communities_directory: z.boolean(),+ realm_welcome_message_custom_text: z.string(),realm_zulip_update_announcements_stream_id: z.number(),server_avatar_changes_disabled: z.boolean(),server_can_summarize_topics: z.boolean(),diff --git a/web/src/tippyjs.ts b/web/src/tippyjs.tsindex 68a2123e655..0c0fe0daaee 100644--- a/web/src/tippyjs.ts+++ b/web/src/tippyjs.ts@@ -869,6 +869,24 @@ export function initialize(): void {},});+ tippy.delegate("body", {+ target: "#welcome_message_custom_text_buttons_container",+ onShow(instance) {+ const $elem = $(instance.reference);+ if ($($elem).find("#send_test_welcome_bot_custom_message").prop("disabled")) {+ const content = $t({defaultMessage: "Welcome Bot message text is required."});+ instance.setContent(content);+ return undefined;+ }+ instance.destroy();+ return false;+ },+ appendTo: () => document.body,+ onHidden(instance) {+ instance.destroy();+ },+ });+tippy.delegate("body", {target: ".topic-edit-save-wrapper",onShow(instance) {diff --git a/web/styles/settings.css b/web/styles/settings.cssindex 271aaaf360d..c839d7a3f3f 100644--- a/web/styles/settings.css+++ b/web/styles/settings.css@@ -129,13 +129,26 @@ h3,gap: 0.5rem;}-.admin-realm-description {+.admin-realm-description,+.admin-realm-welcome-message-custom-text {height: 16em;width: 100%;max-width: 500px;box-sizing: border-box;}+#id_realm_welcome_message_custom_text {+ height: auto;+ margin-bottom: 10px;+}++#welcome_message_custom_text_buttons_container {+ display: inline-flex;+ /* 5px at 16px em */+ gap: 0.3125em;+ align-items: center;+}+.setting_notification_sound,.play_notification_sound {margin-right: 4px;diff --git a/web/styles/zulip.css b/web/styles/zulip.cssindex 4e7d7d363a3..e329ae510d9 100644--- a/web/styles/zulip.css+++ b/web/styles/zulip.css@@ -1351,6 +1351,11 @@ div.topic_edit_spinner .loading_indicator_spinner {width: 100%;}+#invite_welcome_custom_message_text {+ width: 100%;+ box-sizing: border-box;+}+.custom-time-input-value {width: 5ch;margin-right: 15px;diff --git a/web/templates/invite_user_modal.hbs b/web/templates/invite_user_modal.hbsindex 406af8cfde1..864d077f144 100644--- a/web/templates/invite_user_modal.hbs+++ b/web/templates/invite_user_modal.hbs@@ -99,4 +99,27 @@</div></div>{{/if}}+ {{#if is_admin}}+ <div class="input-group">+ {{#if default_welcome_message_custom_text.length}}+ <label class="checkbox display-block modal-field-label">+ <input type="checkbox" id="send_default_realm_welcome_message_custom_text" checked="checked"/>+ <span class="rendered-checkbox"></span>+ {{t 'Send the default Welcome Bot message configured for this organization'}}+ </label>+ {{else}}+ <label class="checkbox display-block modal-field-label">+ <input type="checkbox" id="send_custom_welcome_message_custom_text"/>+ <span class="rendered-checkbox"></span>+ {{t 'Send a custom Welcome Bot message'}}+ </label>+ {{/if}}+ <div id="invite_welcome_message_custom_text_container">+ <label for="invite_welcome_custom_message_text" class="modal-field-label">{{t "Message text" }}</label>+ <textarea id="invite_welcome_custom_message_text" name="invite_welcome_message_custom_text" class="settings_textarea" maxlength="8000" rows="3">+ {{~default_welcome_message_custom_text~}}+ </textarea>+ </div>+ </div>+ {{/if}}</form>diff --git a/web/templates/settings/organization_settings_admin.hbs b/web/templates/settings/organization_settings_admin.hbsindex 69e8d720b23..c50a884b948 100644--- a/web/templates/settings/organization_settings_admin.hbs+++ b/web/templates/settings/organization_settings_admin.hbs@@ -61,6 +61,25 @@<option value="6">{{t "Sunday" }}</option></select></div>++ {{> settings_checkbox+ setting_name="realm_enable_welcome_message_custom_text"+ prefix="id_"+ is_checked=realm_enable_welcome_message_custom_text+ label=admin_settings_label.realm_enable_welcome_message_custom_text+ skip_prop_element=true}}+ <div class="input-group" id="welcome_message_custom_text_container">+ <label for="id_realm_welcome_message_custom_text" class="settings-field-label">+ {{t "Message text" }}+ </label>+ <textarea id="id_realm_welcome_message_custom_text" name="welcome_message_custom_text"+ class="admin-realm-welcome-message-custom-text setting-widget prop-element settings_textarea display-block" maxlength="8000"+ data-setting-widget-type="string" rows="3">{{ realm_welcome_message_custom_text }}</textarea>+ <div id="welcome_message_custom_text_buttons_container">+ {{> ../components/action_button attention="quiet" intent="neutral" label=(t "Send me a test message") id="send_test_welcome_bot_custom_message"}}+ </div>+ </div>+</div></div>diff --git a/web/tests/settings_org.test.cjs b/web/tests/settings_org.test.cjsindex 291273b7315..ec1954c2177 100644--- a/web/tests/settings_org.test.cjs+++ b/web/tests/settings_org.test.cjs@@ -568,6 +568,10 @@ test("set_up", ({override, override_rewire}) => {$("#id_realm_can_create_web_public_channel_group").set_parent($.create("<stub-can-create-web-public-channel-group-parent>"),);+ override(realm, "realm_welcome_message_custom_text", "");+ $("#id_realm_welcome_message_custom_text").set_parent(+ $.create("<stub welcome message custom text>"),+ );// Make our plan not limited so we don't have to stub all the// elements involved in disabling the can_create_groups input.diff --git a/zerver/actions/create_user.py b/zerver/actions/create_user.pyindex da521430dcc..3038be5f5bd 100644--- a/zerver/actions/create_user.py+++ b/zerver/actions/create_user.py@@ -351,10 +351,19 @@ def process_new_human_user(# We have an import loop here; it's intentional, because we want# to keep all the onboarding code in zerver/lib/onboarding.py.- from zerver.lib.onboarding import send_initial_direct_message+ from zerver.lib.onboarding import send_initial_direct_messages_to_user- message_id = send_initial_direct_message(user_profile)- UserMessage.objects.filter(user_profile=user_profile, message_id=message_id).update(+ welcome_message_custom_text = realm.welcome_message_custom_text+ if prereg_user is not None and prereg_user.welcome_message_custom_text is not None:+ welcome_message_custom_text = prereg_user.welcome_message_custom_text+ initial_direct_message_ids = send_initial_direct_messages_to_user(+ user_profile, welcome_message_custom_text=welcome_message_custom_text+ )+ message_id_list = [initial_direct_message_ids.welcome_bot_intro_message_id]+ if initial_direct_message_ids.welcome_bot_custom_message_id is not None:+ message_id_list.append(initial_direct_message_ids.welcome_bot_custom_message_id)++ UserMessage.objects.filter(user_profile=user_profile, message_id__in=message_id_list).update(flags=F("flags").bitor(UserMessage.flags.starred))diff --git a/zerver/actions/invites.py b/zerver/actions/invites.pyindex af3205caf73..a965e1cf05b 100644--- a/zerver/actions/invites.py+++ b/zerver/actions/invites.py@@ -198,6 +198,7 @@ def do_invite_users(invite_expires_in_minutes: int | None,include_realm_default_subscriptions: bool,invite_as: int = PreregistrationUser.INVITE_AS["MEMBER"],+ welcome_message_custom_text: str | None = None,) -> list[tuple[str, str, bool]]:num_invites = len(invitee_emails)@@ -285,6 +286,7 @@ def do_invite_users(realm=realm,include_realm_default_subscriptions=include_realm_default_subscriptions,notify_referrer_on_join=notify_referrer_on_join,+ welcome_message_custom_text=welcome_message_custom_text,)prereg_user.save()stream_ids = [stream.id for stream in streams]@@ -387,12 +389,14 @@ def do_create_multiuse_invite_link(include_realm_default_subscriptions: bool,streams: Sequence[Stream] = [],user_groups: Sequence[NamedUserGroup] = [],+ welcome_message_custom_text: str | None = None,) -> str:realm = referred_by.realminvite = MultiuseInvite.objects.create(realm=realm,referred_by=referred_by,include_realm_default_subscriptions=include_realm_default_subscriptions,+ welcome_message_custom_text=welcome_message_custom_text,)if streams:invite.streams.set(streams)diff --git a/zerver/lib/import_realm.py b/zerver/lib/import_realm.pyindex 6ce9983c527..30a5a5bc9bd 100644--- a/zerver/lib/import_realm.py+++ b/zerver/lib/import_realm.py@@ -41,7 +41,7 @@ from zerver.lib.migration_status import MigrationStatusJson, parse_migration_stafrom zerver.lib.mime_types import guess_typefrom zerver.lib.onboarding import (OnboardingMessageTypeEnum,- send_initial_direct_message,+ send_initial_direct_messages_to_user,send_initial_realm_messages,)from zerver.lib.partial import partial@@ -1948,7 +1948,7 @@ def send_zulip_initial_messages_after_import(realm: Realm, target_channel: Strea).order_by("id")[:BATCH_SIZE]):for user_profile in user_profiles_batch:- send_initial_direct_message(user_profile)+ send_initial_direct_messages_to_user(user_profile)lower_bound_id = user_profiles_batch[-1].iddiff --git a/zerver/lib/onboarding.py b/zerver/lib/onboarding.pyindex 5e362f9dd37..6c3a00672db 100644--- a/zerver/lib/onboarding.py+++ b/zerver/lib/onboarding.py@@ -1,3 +1,4 @@+from dataclasses import dataclassfrom enum import Enumfrom django.conf import settings@@ -9,17 +10,25 @@ from django.utils.translation import override as override_languagefrom zerver.actions.create_realm import setup_realm_internal_botsfrom zerver.actions.message_send import (do_send_messages,+ internal_prep_private_message,internal_prep_stream_message_by_name,internal_send_private_message,)from zerver.actions.reactions import do_add_reactionfrom zerver.lib.emoji import get_emoji_data+from zerver.lib.markdown.fenced_code import get_unused_fencefrom zerver.lib.message import SendMessageRequest, remove_single_newlinesfrom zerver.models import Message, OnboardingUserMessage, Realm, UserProfilefrom zerver.models.recipients import Recipientfrom zerver.models.users import get_system_bot+@dataclass+class InitialDirectMessageIDs:+ welcome_bot_intro_message_id: int+ welcome_bot_custom_message_id: int | None++def missing_any_realm_internal_bots() -> bool:bot_emails = [bot["email_template"] % (settings.INTERNAL_BOT_DOMAIN,)@@ -41,12 +50,17 @@ def create_if_missing_realm_internal_bots() -> None:setup_realm_internal_bots(realm)-def send_initial_direct_message(user: UserProfile) -> int:+def send_initial_direct_messages_to_user(+ user: UserProfile,+ *,+ welcome_message_custom_text: str = "",+) -> InitialDirectMessageIDs:# We adjust the initial Welcome Bot direct message for education organizations.education_organization = user.realm.org_type in (Realm.ORG_TYPES["education_nonprofit"]["id"],Realm.ORG_TYPES["education"]["id"],)+ welcome_bot_messages = []# We need to override the language in this code path, because it's# called from account registration, which is a pre-account API@@ -96,6 +110,20 @@ them in your [Inbox](/#inbox).You can always come back to the [Welcome to Zulip video]({navigation_tour_video_url}) for a quick app overview.""").format(navigation_tour_video_url=settings.NAVIGATION_TOUR_VIDEO_URL)+ welcome_bot_custom_message_string = ""+ # Add welcome bot custom message.+ if welcome_message_custom_text:+ fence = get_unused_fence(welcome_message_custom_text)+ welcome_bot_custom_message_intro_string = _("""+The administrators for this organization would also like to share the following information:""")++ welcome_bot_custom_message_string = f"""+{welcome_bot_custom_message_intro_string}+{fence}quote+{welcome_message_custom_text}+{fence}+"""+content = _("""Hello, and welcome to Zulip!👋 {inform_about_tracked_onboarding_messages_text}@@ -113,16 +141,38 @@ Hello, and welcome to Zulip!👋 {inform_about_tracked_onboarding_messages_text}demo_organization_text=demo_organization_warning_string,)- message_id = internal_send_private_message(- get_system_bot(settings.WELCOME_BOT, user.realm_id),- user,- remove_single_newlines(content),- # Note: Welcome bot doesn't trigger email/push notifications,- # as this is intended to be seen contextually in the application.- disable_external_notifications=True,+ welcome_bot_messages.append(+ internal_prep_private_message(+ get_system_bot(settings.WELCOME_BOT, user.realm_id),+ user,+ remove_single_newlines(content),+ # Note: Welcome bot doesn't trigger email/push notifications,+ # as this is intended to be seen contextually in the application.+ disable_external_notifications=True,+ )+ )++ if welcome_bot_custom_message_string:+ welcome_bot_messages.append(+ internal_prep_private_message(+ get_system_bot(settings.WELCOME_BOT, user.realm_id),+ user,+ welcome_bot_custom_message_string,+ disable_external_notifications=True,+ )+ )++ sent_messages = do_send_messages(welcome_bot_messages)++ welcome_bot_custom_message_id = None+ welcome_bot_intro_message_id = sent_messages[0].message_id+ if welcome_bot_custom_message_string:+ welcome_bot_custom_message_id = sent_messages[1].message_id++ return InitialDirectMessageIDs(+ welcome_bot_intro_message_id=welcome_bot_intro_message_id,+ welcome_bot_custom_message_id=welcome_bot_custom_message_id,)- assert message_id is not None- return message_iddef bot_commands(no_help_command: bool = False) -> str:diff --git a/zerver/management/commands/send_welcome_bot_message.py b/zerver/management/commands/send_welcome_bot_message.pyindex db084b6df02..2cac8ecfc87 100644--- a/zerver/management/commands/send_welcome_bot_message.py+++ b/zerver/management/commands/send_welcome_bot_message.py@@ -4,7 +4,7 @@ from typing import Anyfrom typing_extensions import overridefrom zerver.lib.management import ZulipBaseCommand-from zerver.lib.onboarding import send_initial_direct_message+from zerver.lib.onboarding import send_initial_direct_messages_to_userclass Command(ZulipBaseCommand):@@ -22,4 +22,4 @@ class Command(ZulipBaseCommand):@overridedef handle(self, *args: Any, **options: str) -> None:for user_profile in self.get_users(options, self.get_realm(options), is_bot=False):- send_initial_direct_message(user_profile)+ send_initial_direct_messages_to_user(user_profile)diff --git a/zerver/migrations/0750_multiuseinvite_welcome_message_custom_text_and_more.py b/zerver/migrations/0750_multiuseinvite_welcome_message_custom_text_and_more.pynew file mode 100644index 00000000000..64314bf436f--- /dev/null+++ b/zerver/migrations/0750_multiuseinvite_welcome_message_custom_text_and_more.py@@ -0,0 +1,27 @@+# Generated by Django 5.2.3 on 2025-06-28 19:12++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("zerver", "0749_scheduledmessage_reminder_note_text"),+ ]++ operations = [+ migrations.AddField(+ model_name="realm",+ name="welcome_message_custom_text",+ field=models.TextField(default=""),+ ),+ migrations.AddField(+ model_name="multiuseinvite",+ name="welcome_message_custom_text",+ field=models.TextField(null=True),+ ),+ migrations.AddField(+ model_name="preregistrationuser",+ name="welcome_message_custom_text",+ field=models.TextField(null=True),+ ),+ ]diff --git a/zerver/models/prereg_users.py b/zerver/models/prereg_users.pyindex 21caa9d07d9..e97f1022fe4 100644--- a/zerver/models/prereg_users.py+++ b/zerver/models/prereg_users.py@@ -81,6 +81,10 @@ class PreregistrationUser(models.Model):groups = models.ManyToManyField("zerver.NamedUserGroup")invited_at = models.DateTimeField(auto_now=True)realm_creation = models.BooleanField(default=False)++ # Custom text to be sent to created users in a welcome bot message.+ welcome_message_custom_text = models.TextField(null=True)+# Indicates whether the user needs a password. Users who were# created via SSO style auth (e.g. GitHub/Google) generally do not.password_required = models.BooleanField(default=True)@@ -144,6 +148,9 @@ class MultiuseInvite(models.Model):invited_as = models.PositiveSmallIntegerField(default=PreregistrationUser.INVITE_AS["MEMBER"])include_realm_default_subscriptions = models.BooleanField(default=True)+ # Custom text to be sent to created users in a welcome bot message.+ welcome_message_custom_text = models.TextField(null=True)+# status for tracking whether the invite has been revoked.# If revoked, set to confirmation.settings.STATUS_REVOKED.# STATUS_USED is not supported, because these objects are supposeddiff --git a/zerver/models/realms.py b/zerver/models/realms.pyindex 6a4269c5006..142997c5529 100644--- a/zerver/models/realms.py+++ b/zerver/models/realms.py@@ -165,6 +165,7 @@ class Realm(models.Model):MAX_REALM_DESCRIPTION_LENGTH = 1000MAX_REALM_SUBDOMAIN_LENGTH = 40MAX_REALM_REDIRECT_URL_LENGTH = 128+ MAX_REALM_WELCOME_MESSAGE_CUSTOM_TEXT_LENGTH = 8000INVITES_STANDARD_REALM_DAILY_MAX = 3000MESSAGE_VISIBILITY_LIMITED = 10000@@ -239,6 +240,8 @@ class Realm(models.Model):email_changes_disabled = models.BooleanField(default=False)avatar_changes_disabled = models.BooleanField(default=False)+ welcome_message_custom_text = models.TextField(default="")+POLICY_MEMBERS_ONLY = 1POLICY_ADMINS_ONLY = 2POLICY_FULL_MEMBERS_ONLY = 3@@ -734,6 +737,7 @@ class Realm(models.Model):video_chat_provider=int,waiting_period_threshold=int,want_advertise_in_communities_directory=bool,+ welcome_message_custom_text=str,)REALM_PERMISSION_GROUP_SETTINGS: dict[str, GroupPermissionSetting] = dict(diff --git a/zerver/openapi/python_examples.py b/zerver/openapi/python_examples.pyindex f004536c582..b4184388ee3 100644--- a/zerver/openapi/python_examples.py+++ b/zerver/openapi/python_examples.py@@ -477,6 +477,18 @@ def resend_email_invitation(client: Client) -> None:validate_against_openapi_schema(result, "/invites/{invite_id}/resend", "post", "200")+@openapi_test_function("/realm/test_welcome_bot_custom_message:post")+def test_welcome_bot_custom_message(client: Client) -> None:+ # {code_example|start}+ # Send a test welcome bot custom message with the provided text.+ request = {"welcome_message_custom_text": "Custom Welcome Message Text"}+ result = client.call_endpoint(+ "/realm/test_welcome_bot_custom_message", method="POST", request=request+ )+ # {code_example|end}+ validate_against_openapi_schema(result, "/realm/test_welcome_bot_custom_message", "post", "200")++@openapi_test_function("/users/{user_id}:get")def get_single_user(client: Client) -> None:user_id = 8@@ -2086,6 +2098,7 @@ def test_the_api(client: Client, nonadmin_client: Client, owner_client: Client)test_server_organizations(client)test_errors(client)test_invitations(client)+ test_welcome_bot_custom_message(client)sys.stdout.flush()if REGISTERED_TEST_FUNCTIONS != CALLED_TEST_FUNCTIONS:diff --git a/zerver/openapi/zulip.yaml b/zerver/openapi/zulip.yamlindex 645eb1099d5..bb571ef44c3 100644--- a/zerver/openapi/zulip.yaml+++ b/zerver/openapi/zulip.yaml@@ -5507,6 +5507,15 @@ paths:Zulip [communities directory](/help/communities-directory).**Changes**: New in Zulip 6.0 (feature level 129).+ welcome_message_custom_text:+ type: string+ description: |+ This organization's configured custom message for Welcome Bot+ to send to new user accounts, in Zulip Markdown format.++ Maximum length is 8000 characters.++ **Changes**: New in Zulip 11.0 (feature level 416).zulip_update_announcements_stream_id:type: integerdescription: |@@ -15405,6 +15414,25 @@ paths:type: booleanexample: falsedefault: true+ welcome_message_custom_text:+ description: |+ Custom message text, in Zulip Markdown format, to be sent by the+ Welcome Bot to new users that join the organization via this+ invitation.++ Maximum length is 8000 characters.++ Only organization administrators can use this feature; for other+ users, the value is always `null`.++ - `null`: the organization's default `welcome_message_custom_text` is used.+ - Empty string: no Welcome Bot custom message is sent.+ - Otherwise, the provided string is the custom message.++ **Changes**: New in Zulip 11.0 (feature level 416).+ type: string+ nullable: true+ example: "Welcome to Zulip! We're excited to have you on board."required:- invitee_emails- stream_ids@@ -15595,6 +15623,25 @@ paths:type: booleandefault: falseexample: false+ welcome_message_custom_text:+ description: |+ Custom message text, in Zulip Markdown format, to be sent by the+ Welcome Bot to new users that join the organization via this+ invitation.++ Maximum length is 8000 characters.++ Only organization administrators can use this feature; for other+ users, the value is always `null`.++ - `null`: the organization's default `welcome_message_custom_text` is used.+ - Empty string: no Welcome Bot custom message is sent.+ - Otherwise, the provided string is the custom message.++ **Changes**: New in Zulip 11.0 (feature level 416).+ type: string+ nullable: true+ example: "Welcome to Zulip! We're excited to have you on board."encoding:invite_expires_in_minutes:contentType: application/json@@ -15794,6 +15841,54 @@ paths:}description: |A typical failed JSON response for an invalid email invitation ID:+ /realm/test_welcome_bot_custom_message:+ post:+ operationId: test-welcome-bot-custom-message+ summary: Test welcome bot custom message+ tags: ["server_and_organizations"]+ x-requires-administrator: true+ description: |+ Sends a test Welcome Bot message with custom text to the acting administrator.+ This allows administrators to preview how the welcome message will appear when+ received by new users upon joining the organization.++ **Changes**: New in Zulip 11.0 (feature level 416).+ requestBody:+ required: true+ content:+ application/x-www-form-urlencoded:+ schema:+ type: object+ properties:+ welcome_message_custom_text:+ description: |+ Custom message text, in Zulip Markdown format, to be used for+ this test message.++ Maximum length is 8000 characters.+ type: string+ maxLength: 8000+ example: "Welcome to Zulip! We're excited to have you on board."+ required:+ - welcome_message_custom_text+ responses:+ "200":+ description: Success.+ content:+ application/json:+ schema:+ allOf:+ - $ref: "#/components/schemas/JsonSuccessBase"+ - additionalProperties: false+ properties:+ result: {}+ msg: {}+ ignored_parameters_unsupported: {}+ message_id:+ type: integer+ description: |+ The message_id of the test welcome bot custom message.+ example: {"result": "success", "msg": "", "message_id": 1}/register:post:operationId: register-queue@@ -18965,6 +19060,15 @@ paths:The [organization language][org-lang] for automated messages and invitation emails.[org-lang]: /help/configure-organization-language+ realm_welcome_message_custom_text:+ type: string+ description: |+ Present if `realm` is present in `fetch_event_types`.++ This organization's configured custom message for Welcome Bot+ to send to new user accounts, in Zulip Markdown format.++ **Changes**: New in Zulip 11.0 (feature level 416).realm_description:type: stringdescription: |diff --git a/zerver/tests/test_events.py b/zerver/tests/test_events.pyindex e4384dfd5e5..4e6cb271a0c 100644--- a/zerver/tests/test_events.py+++ b/zerver/tests/test_events.py@@ -4333,6 +4333,10 @@ class RealmPropertyActionTest(BaseAction):bool_tests: list[bool] = [True, False, True]test_values: dict[str, Any] = dict(default_language=["es", "de", "en"],+ welcome_message_custom_text=[+ "Welcome Bot Custom Message",+ "New Welcome Bot Custom Message",+ ],description=["Realm description", "New description"],digest_weekday=[0, 1, 2],message_edit_history_visibility_policy=Realm.MESSAGE_EDIT_HISTORY_VISIBILITY_POLICY_TYPES,diff --git a/zerver/tests/test_home.py b/zerver/tests/test_home.pyindex fa39a818002..8cda9c65581 100644--- a/zerver/tests/test_home.py+++ b/zerver/tests/test_home.py@@ -225,6 +225,7 @@ class HomeTest(ZulipTestCase):"realm_video_chat_provider","realm_waiting_period_threshold","realm_want_advertise_in_communities_directory",+ "realm_welcome_message_custom_text","realm_wildcard_mention_policy","realm_zulip_update_announcements_stream_id","realm_moderation_request_channel_id",diff --git a/zerver/tests/test_invite.py b/zerver/tests/test_invite.pyindex 523aa398d36..f674de3ce84 100644--- a/zerver/tests/test_invite.py+++ b/zerver/tests/test_invite.py@@ -214,6 +214,7 @@ class InviteUserBase(ZulipTestCase):invite_as: int = PreregistrationUser.INVITE_AS["MEMBER"],include_realm_default_subscriptions: bool = False,realm: Realm | None = None,+ welcome_message_custom_text: str | None = None,) -> "TestHttpResponse":"""Invites the specified users to Zulip with the specified streams.@@ -224,6 +225,8 @@ class InviteUserBase(ZulipTestCase):streams should be a list of strings.group_ids should be a list of int.++ welcome_message_custom_text should be a string."""stream_ids = [self.get_stream_id(stream_name, realm=realm) for stream_name in stream_names]@@ -231,20 +234,25 @@ class InviteUserBase(ZulipTestCase):if invite_expires_in is None:invite_expires_in = orjson.dumps(None).decode()+ payload = {+ "invitee_emails": invitee_emails,+ "invite_expires_in_minutes": invite_expires_in,+ "stream_ids": orjson.dumps(stream_ids).decode(),+ "group_ids": orjson.dumps(group_ids).decode() if group_ids else [],+ "invite_as": invite_as,+ "include_realm_default_subscriptions": orjson.dumps(+ include_realm_default_subscriptions+ ).decode(),+ "notify_referrer_on_join": orjson.dumps(notify_referrer_on_join).decode(),+ }++ if welcome_message_custom_text is not None:+ payload["welcome_message_custom_text"] = welcome_message_custom_text+with self.captureOnCommitCallbacks(execute=True):return self.client_post("/json/invites",- {- "invitee_emails": invitee_emails,- "invite_expires_in_minutes": invite_expires_in,- "stream_ids": orjson.dumps(stream_ids).decode(),- "group_ids": orjson.dumps(group_ids).decode() if group_ids else [],- "invite_as": invite_as,- "include_realm_default_subscriptions": orjson.dumps(- include_realm_default_subscriptions- ).decode(),- "notify_referrer_on_join": orjson.dumps(notify_referrer_on_join).decode(),- },+ payload,subdomain=realm.string_id if realm else "zulip",)@@ -2164,6 +2172,165 @@ so we didn't send them an invitation. We did send invitations to everyone else!"self.assertEqual(response.status_code, 302)self.assertEqual(response["Location"], "http://zulip.testserver/")+ def test_invite_welcome_bot_custom_message_from_admin(self) -> None:+ self.login("iago")+ realm = get_realm("zulip")+ welcome_message_custom_text = "Welcome Bot custom message."+ realm_welcome_message_custom_text = "Realm's Welcome Bot message."+ do_set_realm_property(+ realm,+ "welcome_message_custom_text",+ realm_welcome_message_custom_text,+ acting_user=None,+ )++ # Invites when `welcome_message_custom_text` is provided.+ invitee = self.nonreg_email("alice")+ result = self.invite(invitee, [], welcome_message_custom_text=welcome_message_custom_text)+ self.assert_json_success(result)+ self.assertTrue(find_key_by_email(invitee))++ self.submit_reg_form_for_user(invitee, "password")++ received_initial_direct_message = self.get_second_to_last_message()+ received_welcome_bot_custom_message = self.get_last_message()+ self.assertEqual(received_initial_direct_message.sender.email, "[email protected]")+ self.assertTrue(+ received_initial_direct_message.content.startswith("Hello, and welcome to Zulip!")+ )+ self.assertEqual(received_welcome_bot_custom_message.sender.email, "[email protected]")+ self.assertIn(welcome_message_custom_text, received_welcome_bot_custom_message.content)++ # Invites when `welcome_message_custom_text` is not provided.+ invitee = self.nonreg_email("bob")+ result = self.invite(invitee, [])+ self.assert_json_success(result)+ self.assertTrue(find_key_by_email(invitee))++ self.submit_reg_form_for_user(invitee, "password")++ received_initial_direct_message = self.get_second_to_last_message()+ received_welcome_bot_custom_message = self.get_last_message()+ self.assertEqual(received_initial_direct_message.sender.email, "[email protected]")+ self.assertTrue(+ received_initial_direct_message.content.startswith("Hello, and welcome to Zulip!")+ )+ self.assertEqual(received_welcome_bot_custom_message.sender.email, "[email protected]")+ self.assertIn(+ realm_welcome_message_custom_text, received_welcome_bot_custom_message.content+ )++ # Invites when `welcome_message_custom_text` is an empty string.+ self.login("iago")+ invitee = self.nonreg_email("newguy")+ result = self.invite(invitee, [], welcome_message_custom_text="")+ self.assert_json_success(result)+ self.assertTrue(find_key_by_email(invitee))++ self.submit_reg_form_for_user(invitee, "password")++ second_to_last_message = self.get_second_to_last_message()+ received_initial_direct_message = self.get_last_message()+ self.assertNotEqual(second_to_last_message.sender.email, "[email protected]")+ self.assertEqual(received_initial_direct_message.sender.email, "[email protected]")+ self.assertTrue(+ received_initial_direct_message.content.startswith("Hello, and welcome to Zulip!")+ )++ def test_invite_welcome_bot_custom_message_from_member(self) -> None:+ # If a non-admin member is creating an invitaion the Welcome Bot+ # custom message is sent if it is configured in the realm.++ # If the `welcome_message_custom_text` is configured for the realm.+ self.login("hamlet")+ realm = get_realm("zulip")+ welcome_message_custom_text = "Welcome Bot custom message."+ realm_welcome_message_custom_text = "Realm's Welcome Bot message."+ invitee = self.nonreg_email("alice")+ do_set_realm_property(+ realm,+ "welcome_message_custom_text",+ realm_welcome_message_custom_text,+ acting_user=None,+ )++ result = self.invite(invitee, [])+ self.assert_json_success(result)+ self.assertTrue(find_key_by_email(invitee))++ self.submit_reg_form_for_user(invitee, "password")++ received_initial_direct_message = self.get_second_to_last_message()+ received_welcome_bot_custom_message = self.get_last_message()+ self.assertEqual(received_initial_direct_message.sender.email, "[email protected]")+ self.assertTrue(+ received_initial_direct_message.content.startswith("Hello, and welcome to Zulip!")+ )+ self.assertEqual(received_welcome_bot_custom_message.sender.email, "[email protected]")+ self.assertIn(+ realm_welcome_message_custom_text, received_welcome_bot_custom_message.content+ )++ # Non-admin users are not allowed to send customized welcome messages.+ invitee = self.nonreg_email("bob")+ result = self.invite(invitee, [], welcome_message_custom_text=welcome_message_custom_text)+ self.assert_json_error(result, "Must be an organization administrator")++ # If the `welcome_message_custom_text` is not configured for the realm.+ invitee = self.nonreg_email("newguy")+ do_set_realm_property(+ realm,+ "welcome_message_custom_text",+ "",+ acting_user=None,+ )+ result = self.invite(invitee, [])+ self.assert_json_success(result)+ self.assertTrue(find_key_by_email(invitee))++ self.submit_reg_form_for_user(invitee, "password")++ second_to_last_message = self.get_second_to_last_message()+ received_initial_direct_message = self.get_last_message()+ self.assertNotEqual(second_to_last_message.sender.email, "[email protected]")+ self.assertEqual(received_initial_direct_message.sender.email, "[email protected]")+ self.assertTrue(+ received_initial_direct_message.content.startswith("Hello, and welcome to Zulip!")+ )++ def test_invite_welcome_bot_custom_message_changed_after_invite(self) -> None:+ self.login("iago")+ realm = get_realm("zulip")+ realm_welcome_message_custom_text = "Realm's Welcome Bot message."++ # If `welcome_message_custom_text` is `None`, we use the realm's+ # configured message at the time the user accepts the invite. So if the realm's+ # configured message is updated later, the user will receive the updated version.+ self.assertNotEqual(realm.welcome_message_custom_text, realm_welcome_message_custom_text)+ invitee = self.nonreg_email("alice")+ result = self.invite(invitee, [])+ self.assert_json_success(result)+ self.assertTrue(find_key_by_email(invitee))+ do_set_realm_property(+ realm,+ "welcome_message_custom_text",+ realm_welcome_message_custom_text,+ acting_user=None,+ )++ self.submit_reg_form_for_user(invitee, "password")++ received_initial_direct_message = self.get_second_to_last_message()+ received_welcome_bot_custom_message = self.get_last_message()+ self.assertEqual(received_initial_direct_message.sender.email, "[email protected]")+ self.assertTrue(+ received_initial_direct_message.content.startswith("Hello, and welcome to Zulip!")+ )+ self.assertEqual(received_welcome_bot_custom_message.sender.email, "[email protected]")+ self.assertIn(+ realm_welcome_message_custom_text, received_welcome_bot_custom_message.content+ )+class InvitationsTestCase(InviteUserBase):def test_do_get_invites_controlled_by_user(self) -> None:@@ -2829,6 +2996,165 @@ class MultiuseInviteTest(ZulipTestCase):mail.outbox.pop()+ def test_multiuse_invite_welcome_bot_custom_message_from_admin(self) -> None:+ self.login("iago")+ realm = get_realm("zulip")+ welcome_message_custom_text = "Welcome Bot custom message."+ realm_welcome_message_custom_text = "Realm's Welcome Bot message."+ do_set_realm_property(+ realm,+ "welcome_message_custom_text",+ realm_welcome_message_custom_text,+ acting_user=None,+ )++ # Multiuse invites when `welcome_message_custom_text` is provided.+ result = self.client_post(+ "/json/invites/multiuse",+ {+ "welcome_message_custom_text": welcome_message_custom_text,+ },+ )+ invite_link = self.assert_json_success(result)["invite_link"]+ self.check_user_able_to_register(self.nonreg_email("alice"), invite_link)++ received_initial_direct_message = self.get_second_to_last_message()+ received_welcome_bot_custom_message = self.get_last_message()+ self.assertEqual(received_initial_direct_message.sender.email, "[email protected]")+ self.assertTrue(+ received_initial_direct_message.content.startswith("Hello, and welcome to Zulip!")+ )+ self.assertEqual(received_welcome_bot_custom_message.sender.email, "[email protected]")+ self.assertIn(welcome_message_custom_text, received_welcome_bot_custom_message.content)++ # Multiuse invites when `welcome_message_custom_text` is not provided.+ self.login("iago")+ result = self.client_post("/json/invites/multiuse")+ invite_link = self.assert_json_success(result)["invite_link"]+ self.check_user_able_to_register(self.nonreg_email("bob"), invite_link)++ received_initial_direct_message = self.get_second_to_last_message()+ received_welcome_bot_custom_message = self.get_last_message()+ self.assertEqual(received_initial_direct_message.sender.email, "[email protected]")+ self.assertTrue(+ received_initial_direct_message.content.startswith("Hello, and welcome to Zulip!")+ )+ self.assertEqual(received_welcome_bot_custom_message.sender.email, "[email protected]")+ self.assertIn(+ realm_welcome_message_custom_text, received_welcome_bot_custom_message.content+ )++ # Multiuse invites when `welcome_message_custom_text` is an empty string.+ self.login("iago")+ result = self.client_post(+ "/json/invites/multiuse",+ {+ "welcome_message_custom_text": "",+ },+ )+ invite_link = self.assert_json_success(result)["invite_link"]+ self.check_user_able_to_register(self.nonreg_email("newguy"), invite_link)++ second_to_last_message = self.get_second_to_last_message()+ received_initial_direct_message = self.get_last_message()+ self.assertFalse(second_to_last_message.content.startswith("Hello, and welcome to Zulip!"))+ self.assertEqual(received_initial_direct_message.sender.email, "[email protected]")+ self.assertTrue(+ received_initial_direct_message.content.startswith("Hello, and welcome to Zulip!")+ )++ def test_multiuse_invite_welcome_bot_custom_message_from_member(self) -> None:+ # If a non-admin member is creating an invitaion the Welcome Bot+ # custom message is sent if it is configured in the realm.++ # If the `welcome_message_custom_text` is configured for the realm.+ self.login("hamlet")+ realm = get_realm("zulip")+ members_group = NamedUserGroup.objects.get(+ name=SystemGroups.MEMBERS, realm=realm, is_system_group=True+ )+ welcome_message_custom_text = "Welcome Bot custom message."+ realm_welcome_message_custom_text = "Realm's Welcome Bot message."+ do_change_realm_permission_group_setting(+ realm, "create_multiuse_invite_group", members_group, acting_user=None+ )+ do_set_realm_property(+ realm,+ "welcome_message_custom_text",+ realm_welcome_message_custom_text,+ acting_user=None,+ )++ result = self.client_post("/json/invites/multiuse")+ invite_link = self.assert_json_success(result)["invite_link"]+ self.check_user_able_to_register(self.nonreg_email("alice"), invite_link)++ received_initial_direct_message = self.get_second_to_last_message()+ received_welcome_bot_custom_message = self.get_last_message()+ self.assertEqual(received_initial_direct_message.sender.email, "[email protected]")+ self.assertTrue(+ received_initial_direct_message.content.startswith("Hello, and welcome to Zulip!")+ )+ self.assertEqual(received_welcome_bot_custom_message.sender.email, "[email protected]")+ self.assertIn(+ realm_welcome_message_custom_text, received_welcome_bot_custom_message.content+ )++ # Non-admin users are not allowed to send customized welcome messages.+ result = self.client_post(+ "/json/invites/multiuse", {"welcome_message_custom_text": welcome_message_custom_text}+ )+ self.assert_json_error(result, "Must be an organization administrator")++ # If the `welcome_message_custom_text` is not configured for the realm.+ do_set_realm_property(+ realm,+ "welcome_message_custom_text",+ "",+ acting_user=None,+ )+ result = self.client_post("/json/invites/multiuse")+ invite_link = self.assert_json_success(result)["invite_link"]+ self.check_user_able_to_register(self.nonreg_email("newguy"), invite_link)++ second_to_last_message = self.get_second_to_last_message()+ received_initial_direct_message = self.get_last_message()+ self.assertFalse(second_to_last_message.content.startswith("Hello, and welcome to Zulip!"))+ self.assertEqual(received_initial_direct_message.sender.email, "[email protected]")+ self.assertTrue(+ received_initial_direct_message.content.startswith("Hello, and welcome to Zulip!")+ )++ def test_multiuse_invite_welcome_bot_custom_message_changed_after_invite(self) -> None:+ self.login("iago")+ realm = get_realm("zulip")+ realm_welcome_message_custom_text = "Realm's Welcome Bot message."++ # If `welcome_message_custom_text` is `None`, we use the realm's+ # configured message at the time the user accepts the invite. So if the realm's+ # configured message is updated later, the user will receive the updated version.+ self.assertNotEqual(realm.welcome_message_custom_text, realm_welcome_message_custom_text)+ result = self.client_post("/json/invites/multiuse")+ invite_link = self.assert_json_success(result)["invite_link"]+ do_set_realm_property(+ realm,+ "welcome_message_custom_text",+ realm_welcome_message_custom_text,+ acting_user=None,+ )+ self.check_user_able_to_register(self.nonreg_email("alice"), invite_link)++ received_initial_direct_message = self.get_second_to_last_message()+ received_welcome_bot_custom_message = self.get_last_message()+ self.assertEqual(received_initial_direct_message.sender.email, "[email protected]")+ self.assertTrue(+ received_initial_direct_message.content.startswith("Hello, and welcome to Zulip!")+ )+ self.assertEqual(received_welcome_bot_custom_message.sender.email, "[email protected]")+ self.assertIn(+ realm_welcome_message_custom_text, received_welcome_bot_custom_message.content+ )+def test_valid_multiuse_link(self) -> None:email1 = self.nonreg_email("test")email2 = self.nonreg_email("test1")diff --git a/zerver/tests/test_realm.py b/zerver/tests/test_realm.pyindex e58573f65e5..37c65933354 100644--- a/zerver/tests/test_realm.py+++ b/zerver/tests/test_realm.py@@ -2049,6 +2049,10 @@ class RealmAPITest(ZulipTestCase):test_values: dict[str, Any] = dict(default_language=["de", "en"],default_code_block_language=["javascript", ""],+ welcome_message_custom_text=[+ "Welcome Bot Custom Message",+ "New Welcome Bot Custom Message",+ ],description=["Realm description", "New description"],digest_weekday=[0, 1, 2],message_edit_history_visibility_policy=Realm.MESSAGE_EDIT_HISTORY_VISIBILITY_POLICY_TYPES,diff --git a/zerver/tests/test_welcome_bot_custom_message.py b/zerver/tests/test_welcome_bot_custom_message.pynew file mode 100644index 00000000000..15ee20509f6--- /dev/null+++ b/zerver/tests/test_welcome_bot_custom_message.py@@ -0,0 +1,44 @@+from typing_extensions import override++from zerver.lib.test_classes import ZulipTestCase+++class WelcomeBotCustomMessageTest(ZulipTestCase):+ @override+ def setUp(self) -> None:+ super().setUp()+ self.user_profile = self.example_user("iago")++ def test_empty_welcome_bot_custom_message(self) -> None:+ user = self.example_user("desdemona")+ self.login_user(user)++ result = self.client_post(+ "/json/realm/test_welcome_bot_custom_message",+ {"welcome_message_custom_text": ""},+ )+ self.assert_json_error(result, "Message must not be empty")++ def test_welcome_bot_custom_message(self) -> None:+ user = self.example_user("desdemona")+ self.login_user(user)+ welcome_message_custom_text = "Welcome Bot custom message for testing"++ result = self.client_post(+ "/json/realm/test_welcome_bot_custom_message",+ {"welcome_message_custom_text": welcome_message_custom_text},+ )+ response_dict = self.assert_json_success(result)+ welcome_bot_custom_message_id = response_dict["message_id"]++ received_welcome_bot_message = self.get_second_to_last_message()+ received_welcome_bot_custom_message = self.get_last_message()++ self.assertEqual(received_welcome_bot_message.sender.email, "[email protected]")+ self.assertTrue(+ received_welcome_bot_message.content.startswith("Hello, and welcome to Zulip!")+ )++ self.assertEqual(received_welcome_bot_custom_message.sender.email, "[email protected]")+ self.assertIn(welcome_message_custom_text, received_welcome_bot_custom_message.content)+ self.assertEqual(welcome_bot_custom_message_id, received_welcome_bot_custom_message.id)diff --git a/zerver/views/invite.py b/zerver/views/invite.pyindex c752db92572..2eb495068fd 100644--- a/zerver/views/invite.py+++ b/zerver/views/invite.py@@ -6,7 +6,7 @@ from django.db import transactionfrom django.http import HttpRequest, HttpResponsefrom django.utils.timezone import now as timezone_nowfrom django.utils.translation import gettext as _-from pydantic import Json+from pydantic import Json, StringConstraintsfrom confirmation import settings as confirmation_settingsfrom zerver.actions.invites import (@@ -24,7 +24,14 @@ from zerver.lib.streams import access_stream_by_id, get_streams_to_which_user_cafrom zerver.lib.typed_endpoint import ApiParamConfig, PathOnly, typed_endpointfrom zerver.lib.typed_endpoint_validators import check_int_in_validatorfrom zerver.lib.user_groups import UserGroupMembershipDetails, access_user_group_for_update-from zerver.models import MultiuseInvite, NamedUserGroup, PreregistrationUser, Stream, UserProfile+from zerver.models import (+ MultiuseInvite,+ NamedUserGroup,+ PreregistrationUser,+ Realm,+ Stream,+ UserProfile,+)# Convert INVITATION_LINK_VALIDITY_DAYS into minutes.# Because mypy fails to correctly infer the type of the validator, we want this constant@@ -137,6 +144,12 @@ def invite_users_backend(invitee_emails_raw: Annotated[str, ApiParamConfig("invitee_emails")],notify_referrer_on_join: Json[bool] = True,stream_ids: Json[list[int]],+ welcome_message_custom_text: Annotated[+ str | None,+ StringConstraints(+ max_length=Realm.MAX_REALM_WELCOME_MESSAGE_CUSTOM_TEXT_LENGTH,+ ),+ ] = None,) -> HttpResponse:if not user_profile.can_invite_users_by_email():# Guest users case will not be handled here as it will@@ -160,6 +173,9 @@ def invite_users_backend(streams = access_streams_for_invite(stream_ids, user_profile)user_groups = access_user_groups_for_invite(group_ids, user_profile)+ if welcome_message_custom_text is not None and not user_profile.is_realm_admin:+ raise JsonableError(_("Must be an organization administrator"))+skipped = do_invite_users(user_profile,invitee_emails,@@ -169,6 +185,7 @@ def invite_users_backend(invite_expires_in_minutes=invite_expires_in_minutes,include_realm_default_subscriptions=include_realm_default_subscriptions,invite_as=invite_as,+ welcome_message_custom_text=welcome_message_custom_text,)if skipped:@@ -246,6 +263,12 @@ def generate_multiuse_invite_backend(] = PreregistrationUser.INVITE_AS["MEMBER"],invite_expires_in_minutes: Json[int | None] = INVITATION_LINK_VALIDITY_MINUTES,stream_ids: Json[list[int]] | None = None,+ welcome_message_custom_text: Annotated[+ str | None,+ StringConstraints(+ max_length=Realm.MAX_REALM_WELCOME_MESSAGE_CUSTOM_TEXT_LENGTH,+ ),+ ] = None,) -> HttpResponse:if stream_ids is None:stream_ids = []@@ -266,6 +289,9 @@ def generate_multiuse_invite_backend(streams = access_streams_for_invite(stream_ids, user_profile)user_groups = access_user_groups_for_invite(group_ids, user_profile)+ if welcome_message_custom_text is not None and not user_profile.is_realm_admin:+ raise JsonableError(_("Must be an organization administrator"))+invite_link = do_create_multiuse_invite_link(user_profile,invite_as,@@ -273,5 +299,6 @@ def generate_multiuse_invite_backend(include_realm_default_subscriptions,streams,user_groups,+ welcome_message_custom_text,)return json_success(request, data={"invite_link": invite_link})diff --git a/zerver/views/realm.py b/zerver/views/realm.pyindex c9b067cabcc..7f88cc79364 100644--- a/zerver/views/realm.py+++ b/zerver/views/realm.py@@ -201,6 +201,12 @@ def update_realm(zulip_update_announcements_stream_id: Json[int] | None = None,# Note: push_notifications_enabled and push_notifications_enabled_end_timestamp# are not offered here as it is maintained by the server, not via the API.+ welcome_message_custom_text: Annotated[+ str | None,+ StringConstraints(+ max_length=Realm.MAX_REALM_WELCOME_MESSAGE_CUSTOM_TEXT_LENGTH,+ ),+ ] = None,) -> HttpResponse:# Realm object is being refetched here to make sure that we# do not use stale object from cache which can happen when adiff --git a/zerver/views/registration.py b/zerver/views/registration.pyindex f02de9c34f8..bb8c2bab989 100644--- a/zerver/views/registration.py+++ b/zerver/views/registration.py@@ -951,6 +951,7 @@ def prepare_activation_url(realm: Realm | None,streams: Iterable[Stream] | None = None,user_groups: Iterable[NamedUserGroup] | None = None,+ welcome_message_custom_text: str | None = None,) -> str:"""Send an email with a confirmation link to the provided e-mail so the user@@ -970,6 +971,9 @@ def prepare_activation_url(if include_realm_default_subscriptions is not None:prereg_user.include_realm_default_subscriptions = include_realm_default_subscriptions+ if welcome_message_custom_text is not None:+ prereg_user.welcome_message_custom_text = welcome_message_custom_text+if invited_as is not None or include_realm_default_subscriptions is not None:prereg_user.save()@@ -1451,6 +1455,7 @@ def accounts_home(user_groups_to_subscribe = Noneinvited_as = Noneinclude_realm_default_subscriptions = None+ welcome_message_custom_text = Noneif multiuse_object:# multiuse_object's realm should have been validated by the caller,@@ -1463,6 +1468,7 @@ def accounts_home(from_multiuse_invite = Trueinvited_as = multiuse_object.invited_asinclude_realm_default_subscriptions = multiuse_object.include_realm_default_subscriptions+ welcome_message_custom_text = multiuse_object.welcome_message_custom_textif request.method == "POST":form = HomepageForm(@@ -1502,6 +1508,7 @@ def accounts_home(invited_as=invited_as,include_realm_default_subscriptions=include_realm_default_subscriptions,multiuse_invite=multiuse_object,+ welcome_message_custom_text=welcome_message_custom_text,)try:send_confirm_registration_email(email, activation_url, request=request, realm=realm)diff --git a/zerver/views/welcome_bot_custom_message.py b/zerver/views/welcome_bot_custom_message.pynew file mode 100644index 00000000000..7eef4cb9495--- /dev/null+++ b/zerver/views/welcome_bot_custom_message.py@@ -0,0 +1,37 @@+from typing import Annotated++from django.http import HttpRequest, HttpResponse+from django.utils.translation import gettext as _+from pydantic import StringConstraints++from zerver.decorator import require_realm_admin+from zerver.lib.exceptions import JsonableError+from zerver.lib.onboarding import send_initial_direct_messages_to_user+from zerver.lib.response import json_success+from zerver.lib.typed_endpoint import typed_endpoint+from zerver.models.realms import Realm+from zerver.models.users import UserProfile+++@require_realm_admin+@typed_endpoint+def send_test_welcome_bot_custom_message(+ request: HttpRequest,+ user_profile: UserProfile,+ *,+ welcome_message_custom_text: Annotated[+ str,+ StringConstraints(+ max_length=Realm.MAX_REALM_WELCOME_MESSAGE_CUSTOM_TEXT_LENGTH,+ ),+ ],+) -> HttpResponse:+ if len(welcome_message_custom_text) == 0:+ raise JsonableError(_("Message must not be empty"))++ message_ids = send_initial_direct_messages_to_user(+ user_profile, welcome_message_custom_text=welcome_message_custom_text+ )+ welcome_bot_custom_message_id = message_ids.welcome_bot_custom_message_id+ assert welcome_bot_custom_message_id is not None+ return json_success(request, data={"message_id": welcome_bot_custom_message_id})diff --git a/zproject/urls.py b/zproject/urls.pyindex edba6b8e8f6..de7ce591887 100644--- a/zproject/urls.py+++ b/zproject/urls.py@@ -270,6 +270,7 @@ from zerver.views.video_calls import (make_zoom_video_call,register_zoom_user,)+from zerver.views.welcome_bot_custom_message import send_test_welcome_bot_custom_messagefrom zerver.views.zephyr import webathena_kerberos_loginfrom zproject import dev_urls@@ -337,6 +338,8 @@ v1_api_and_json_patterns = [),# realm/deactivate -> zerver.views.deactivate_realmrest_path("realm/deactivate", POST=deactivate_realm),+ # realm/test_welcome_bot_custom_message -> zerver.views.welcome_bot_custom_message+ rest_path("realm/test_welcome_bot_custom_message", POST=send_test_welcome_bot_custom_message),# users -> zerver.views.usersrest_path("users", GET=(get_members_backend, {"allow_anonymous_user_web"}), POST=create_user_backend