Retry PK API if it doesn't return a message
This commit is contained in:
		| @@ -142,8 +142,19 @@ async function syncUser(author, pkMessage, roomID) { | ||||
| } | ||||
|  | ||||
| /** @returns {Promise<Ty.PkMessage>} */ | ||||
| function fetchMessage(messageID) { | ||||
| 	return fetch(`https://api.pluralkit.me/v2/messages/${messageID}`).then(res => res.json()) | ||||
| async function fetchMessage(messageID) { | ||||
| 	// Their backend is weird. Sometimes it says "message not found" (code 20006) on the first try, so we make multiple attempts. | ||||
| 	let attempts = 0 | ||||
| 	do { | ||||
| 		var res = await fetch(`https://api.pluralkit.me/v2/messages/${messageID}`) | ||||
| 		if (res.ok) return res.json() | ||||
|  | ||||
| 		// I think the backend needs some time to update. | ||||
| 		await new Promise(resolve => setTimeout(resolve, 2000)) | ||||
| 	} while (++attempts < 3) | ||||
|  | ||||
| 	const errorMessage = await res.json() | ||||
| 	throw new Error(`PK API returned an error after ${attempts} tries: ${JSON.stringify(errorMessage)}`) | ||||
| } | ||||
|  | ||||
| module.exports._memberToStateContent = memberToStateContent | ||||
|   | ||||
| @@ -39,15 +39,8 @@ async function sendMessage(message, channel, guild, row) { | ||||
| 	} else if (row && row.speedbump_webhook_id === message.webhook_id) { | ||||
| 		// Handle the PluralKit public instance | ||||
| 		if (row.speedbump_id === "466378653216014359") { | ||||
| 			const root = await registerPkUser.fetchMessage(message.id) | ||||
| 			// Member is null if member was deleted. We just got this message, so member surely exists. | ||||
| 			if (!root.member) { | ||||
| 				const e = new Error("PK API did not return a member") | ||||
| 				message["__pk_response__"] = root | ||||
| 				console.error(root) | ||||
| 				throw e | ||||
| 			} | ||||
| 			senderMxid = await registerPkUser.syncUser(message.author, root, roomID) | ||||
| 			const pkMessage = await registerPkUser.fetchMessage(message.id) | ||||
| 			senderMxid = await registerPkUser.syncUser(message.author, pkMessage, roomID) | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
|   | ||||
		Reference in New Issue
	
	Block a user
	 Cadence Ember
					Cadence Ember